Reputation: 1110
I read online tutorial it states: Actually, the most reliable conversion check is either a regexp or isNumeric below:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n)
}
My question is why this function can not be simplified to:
function isNumeric(n) {
return isFinite(n)
}
Upvotes: 3
Views: 595
Reputation: 1073968
My question is why this function can not be simplified to:
function isNumeric(n) { return isFinite(n) }
It can't, no, you want that parseFloat
in there if there's any chance n
may not be a number to start with. But it could be simplified to:
function isNumeric(n) {
return isFinite(parseFloat(n));
}
...because isFinite(NaN)
is false, which is what your function returned for unparseable numbers anyway.
It's worth noting that parseFloat
will stop at the first invalid character and return whatever number it found up to that point, so parseFloat("123abc")
is 123
, not NaN
. If you want to validate that the entire string can be correctly parsed as floating point, use +
or Number()
:
function isNumeric(n) {
return isFinite(+n); // Or: return isFinite(Number(n));
}
Now, if you know for sure that n
will always already be a number (not a boolean or a string or something), then yes, you could skip the parsing stage.
Upvotes: 2
Reputation: 2821
Well no you can't use is finite as that will only return true for a finite number.
For example isFinite(1/0)
returns false.
Infinity is a number its just not finite.
I'd suggest looking at how the big libraries do it for example:
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]';
}
Upvotes: 0
Reputation: 4025
Because isFinite(n) will return true for non-numeric values, for example:
alert(isFinite(false)); // displays true
Upvotes: 2