By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,851 Members | 1,097 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,851 IT Pros & Developers. It's quick & easy.

When is something a number and not a number

Claus Mygind
100+
P: 571
Using the following coding

Expand|Select|Wrap|Line Numbers
  1.  
  2. <input type text id="myField" value ="" />
  3.  
  4. var cThisVal = parseFloat( document.getElementById("myField").value)
  5.  
  6.  
When I check the value of "cThisVal" and see the response is NaN not a number.

I then test to see if it a number like this.

Expand|Select|Wrap|Line Numbers
  1. typeof cThisVal == "number"  evaluates to false
  2. typeof document.getElementById("myField").value == "number"  evaluates to true
So am I to assume that "parsefloat" makes cThisValue a number even though it is not. Also if it evaluated as a number, what is the value?
Sep 30 '08 #1
Share this Question
Share on Google+
2 Replies


Claus Mygind
100+
P: 571
Ok I think I got that one figured out. just use the "isNaN(cThisVal)" function instead to get the right result.
Sep 30 '08 #2

gits
Expert Mod 5K+
P: 5,235
yep ... in such cases the isNaN() method could/should be used. for parseFloat() it is correct that this method will cast the string that is given to it to a js-floating number ... and when it cannot be parsed correctly then the method returns NaN (not a number) ... but we cannot really rely on that ... have a look at the following examples:

Expand|Select|Wrap|Line Numbers
  1. var s = '1.foo';
  2. alert(parseFloat(s)); // alerts 1
  3.  
  4. var s1 = '.1s';
  5. alert(parseFloat(s1)); // alerts 0.1
so even when the value is not a number parseFloat() does the 'best' to parse it and returns the number that could be parsed by just leaving out the characters that invalidate the number ... so we would have (at least we could have) a logical error when we would rely on parseFloat()'s return to decide the value was a number or not :) because both of them in the example where not ... but in both of the cases we don't get a NaN ...

kind regards
Sep 30 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.