What's the cleanest, most effective way to validate decimal numbers in JavaScript?
Bonus points for:
- Clarity. Solution should be clean and simple.
- Cross-platform.
Test cases:
01. IsNumeric('-1') => true
02. IsNumeric('-1.5') => true
03. IsNumeric('0') => true
04. IsNumeric('0.42') => true
05. IsNumeric('.42') => true
06. IsNumeric('99,999') => false
07. IsNumeric('0x89f') => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3') => false
10. IsNumeric('') => false
11. IsNumeric('blah') => false
Only problem I had with @CMS's answer is the exclusion of
NaN
and Infinity, which are useful numbers for many situations. One way to check forNaN
's is to check for numeric values that don't equal themselves,NaN != NaN
! So there are really 3 tests you'd like to deal with ...My isComparableNumber is pretty close to another elegant answer, but handles hex and other string representations of numbers.
If I'm not mistaken, this should match any valid JavaScript number value, excluding constants (
Infinity
,NaN
) and the sign operators+
/-
(because they are not actually part of the number as far as I concerned, they are separate operators):I needed this for a tokenizer, where sending the number to JavaScript for evaluation wasn't an option... It's definitely not the shortest possible regular expression, but I believe it catches all the finer subtleties of JavaScript's number syntax.
Valid numbers would include:
Invalid numbers would be
Yahoo! UI uses this:
This works for 0x23 type numbers as well.
To me, this is the best way:
A couple of tests to add:
I came up with this:
The solution covers: