2

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.

8
  • new Number(), not just Number(). Or rather - parseInt(xxx, 10) Commented May 16, 2013 at 7:40
  • typeof(NaN) === "number" Commented May 16, 2013 at 7:41
  • Becaue the NaN value is of type number as well? Commented May 16, 2013 at 7:41
  • What are the values of paymentTotal and paymentReceived? Commented May 16, 2013 at 7:41
  • 2
    Note that when you use parseInt, you should always include 10 as a second parameter (otherwise numbers starting with a 0 will be read as base 8!) Commented May 16, 2013 at 7:44

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

0

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

-1

try below code

console.log(Number(paymentTotal)-Number(payementReceived));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.