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
This should work. Some of the functions provided here are flawed, also should be faster than any other function here.
Explained:
Create a copy of itself, then converts the number into float, then compares itself with the original number, if it is still a number, (whether integer or float) , and matches the original number, that means, it is indeed a number.
It works with numeric strings as well as plain numbers. Does not work with hexadecimal numbers.
Warning: use at your own risk, no guarantees.
It can be done without RegExp as
If n is numeric
Number(n)
will return the numeric value andtoString()
will turn it back to a string. But if n isn't numericNumber(n)
will returnNaN
so it won't match the originaln
You can minimize this function in a lot of way, and you can also implement it with a custom regex for negative values or custom charts:
I'm using simpler solution:
I realize this has been answered many times, but the following is a decent candidate which can be useful in some scenarios.
it should be noted that it assumes that '.42' is NOT a number, and '4.' is NOT a number, so this should be taken into account.
The
isDecimal
passes the following test:The idea here is that every number or integer has one "canonical" string representation, and every non-canonical representation should be rejected. So we cast to a number and back, and see if the result is the original string.
Whether these functions are useful for you depends on the use case. One feature is that distinct strings represent distinct numbers (if both pass the
isNumber()
test).This is relevant e.g. for numbers as object property names.