I have a function having following lines:
payementReceived=data.toJSON().total;
paymentTotal=$("#paymentTotal").html();
console.log(typeof(parseInt(paymentTotal)));
console.log(typeof(parseInt(paymentReceived)));
console.log(parseInt(paymentTotal)-parseInt(paymentReceived));
I get the following in console
number
number
NaN
i don't understand if both are numbers then why it isn't able to give the proper substraction result.
4 Answers 4
The values are number in that their contents are a number, but it doesn't mean that the number is valid.
typeof NaN === 'number'
If you are getting a NaN back from your subtraction, one or both of your input values are invalid numbers.
Comments
problem is because of the undefined varaible used "paymentReceived" if you are sure that the result is a number you can always use parseInt
console.log(parseInt(paymentTotal)-parseInt(payementReceived));
Comments
Just a funny idea :
if (typeof n === "number" && n+1 !== n) {
// this is a valid number
}
invalid+1 will still be invalid so it could check for invalid numbers.
Comments
try below code
console.log(Number(paymentTotal)-Number(payementReceived));
new Number(), not justNumber(). Or rather -parseInt(xxx, 10)typeof(NaN) === "number"NaNvalue is of typenumberas well?paymentTotalandpaymentReceived?parseInt, you should always include10as a second parameter (otherwise numbers starting with a 0 will be read as base 8!)