Numeric Test

There are a large number of ways in JavaScript for testing if a variable contains a number. The shortest code to perform such a test is to do a simple comparison as follows (where 'n' is the variable that you want to test for containing a number):

if (n == +n) {...}

The value on the right is converted to a number because of the + preceding it and the == tests that the value has not been changed as a result of converting the value to a number (as non-numbers would be converted to the number zero). This does have the disadvantage of using the comparison test that doesn't compare the type which should generally be avoided where possible when writing comparisons but it is unavoidable if you are using a comparison to test if a variable can be converted to a particular type (given that all values input through forms start out as text strings).

Note that the values that JavaScript accepts as numbers covers quite a large range and if you had previously set one of the following statements then the above comparison would return true.

n = parseFloat('10e12'); // 1000000000000

JavaScript does contain a function for testing if a variable contains a number that is equivalent to the above comparison but using it instead of the above comparison means that you need slightly longer code (nine characters instead of five) which is insignificant but also the way the function works you need to reverse the result returned which makes the code slightly harder to read.

if (!isNaN(n)) {...}

If you do use this function call for testing if the field does or doesn't contain a number then you should use it consistently and not use the shorter comparison test.

Note that both of these comparisons allow plus and minus infinity as numeric values. If instead you want to exclude those two values and only accept numbers that have actual values that can be used in calculations then you should use a different built in function call for your numeric testing which is insignificantly longer again (11 characters) but which doesn't have the issue with needing to have the not operator applied and so is far easier to read.

if (isFinite(n)) {...}

Of course all these tests assume that you already have the number stored in the variable as a number without any of the formatting that you might want to apply for display purposes and which your visitors might mistakenly enter when they are inputting the number into a form. If you are going to allow your visitors to enter formatted numbers you would need to strip out any formatting they applied before being able to test if the field contained a number in which case all you would be left with after stripping out everything that isn't a number would be a number and so testing if it is a number or not would then be unnecessary.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow