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
I realize the original question did not mention jQuery, but if you do use jQuery, you can do:
Simple.
https://api.jquery.com/jQuery.isNumeric/ (as of jQuery 1.7)
I'd like to add the following:
Positive hex numbers start with
0x
and negative hex numbers start with-0x
. Positive oct numbers start with0
and negative oct numbers start with-0
. This one takes most of what has already been mentioned into consideration, but includes hex and octal numbers, negative scientific, Infinity and has removed decimal scientific (4e3.2
is not valid).None of the answers return
false
for empty strings, a fix for that...My solution,
It appears to work in every situation, but I might be wrong.
Yeah, the built-in
isNaN(object)
will be much faster than any regex parsing, because it's built-in and compiled, instead of interpreted on the fly.Although the results are somewhat different to what you're looking for (try it):
To check if a variable contains a valid number and not just a String which looks like a number,
Number.isFinite(value)
can be used.This is part of the language since ES2015
Examples: