Check numeric value in javascript
I am reading an online tutorial that says: Actually, the most reliable conversion checker is either regex or isNumeric below:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n)
}
My question is why this function cannot be simplified:
function isNumeric(n) {
return isFinite(n)
}
source to share
My question is why this function cannot be simplified:
function isNumeric(n) { return isFinite(n) }
You can't, no, you want to get parseFloat
there if there is a chance that there n
might not be a number to start with. But this can be simplified:
function isNumeric(n) {
return isFinite(parseFloat(n));
}
... because it isFinite(NaN)
is false, which returns your function for unmatched numbers anyway.
It's worth noting that it parseFloat
will stop at the first invalid character and return any number found up to that point, so parseFloat("123abc")
- 123
rather than NaN
. If you want to check that the entire string can be parsed correctly as floating point, use +
either Number()
:
function isNumeric(n) {
return isFinite(+n); // Or: return isFinite(Number(n));
}
Now, if you know for sure that it n
will always already be a number (not a boolean or a string or whatever), then yes, you can skip the parsing step. p>
source to share
Well no, you can't use of course, as this will only return true for a finite number.
For example, it isFinite(1/0)
returns false.
Infinity is a number that just isn't finite.
I would suggest looking at how large libraries do it:
Jquery
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
return obj - parseFloat( obj ) >= 0;
}
Underscore.js
function isNumber(obj) {
return toString.call(obj) == '[object Number]';
}
source to share