• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

2. Numbers and Dates > 2.2. Testing a Number’s Validity

Testing a Number’s Validity

NN 3, IE 4

Problem

You want to be sure a value is a number before performing a math operation on it.

Solution

If the value you’re testing can come from any kind of source, the safest bet is to use the typeof operator on the value. Applying this operator to any numeric value evaluates to the string number. Therefore, using it in a conditional expression looks like this:

if (typeof someVal =  = "number") {
    // OK, operate on the value numerically
}

But some JavaScript methods, such as parseInt( ) and parseFloat( ) , return a special value, NaN (“not a number”), signifying that they were unable to derive the number you desired. Operations expecting numeric operands or arguments that encounter values evaluating to NaN also generally return NaN. To test for this condition, use the isNaN( ) method, which returns true if the value is not a number. For example:


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint