Is this thing a number?
TL;DR - do not use only isNaN
for this and write a lot of tests.
StackOverflow implementation (so far ✅):
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Facebook implementation (❌ fails for many values like null
, booleans, Date object, empty strings, ...):
function isNumber(number) {
return !isNaN(number) && isFinite(number);
}
@cookielab implementation (❌ fails for values like 7.2acdgs
and it's not multiplatform):
function isNumeric(n) {
return Number.isFinite(Number.parseFloat(n));
}
Please note that isNaN
and Number.isNaN
differs significantly (isNaN
performs a type conversion). The same for isFinite
vs Number.isFinite
:
In comparison to the global
isFinite()
function, this method doesn't forcibly convert the parameter to a number. This means only values of the type number, that are also finite, returntrue
.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite
Number.isFinite('0'); // false, would've been true with global isFinite('0')
Number.isFinite(null); // false, would've been true with global isFinite(null)
Polyfill (to understand the difference better):
Number.isFinite =
Number.isFinite ||
function (value) {
return typeof value === 'number' && isFinite(value);
};