When is something a number and not a number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Claus Mygind
    Contributor
    • Mar 2008
    • 571

    When is something a number and not a number

    Using the following coding

    Code:
    	
    <input type text id="myField" value ="" />
    
    var cThisVal = parseFloat( document.getElementById("myField").value)
    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.

    Code:
    typeof cThisVal == "number"  evaluates to false
    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?
  • Claus Mygind
    Contributor
    • Mar 2008
    • 571

    #2
    Ok I think I got that one figured out. just use the "isNaN(cThisVal )" function instead to get the right result.

    Comment

    • gits
      Recognized Expert Moderator Expert
      • May 2007
      • 5388

      #3
      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:

      [CODE=javascript]var s = '1.foo';
      alert(parseFloa t(s)); // alerts 1

      var s1 = '.1s';
      alert(parseFloa t(s1)); // alerts 0.1[/CODE]
      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

      Comment

      Working...