Is there is any function like isNumeric
in pure JavaScript?
I know jQuery has this function to check the integers.
There's no isNumeric()
type of function, but you could add your own:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
NOTE: Since parseInt()
is not a proper way to check for numeric it should NOT be used.
parseInt
was the wrong way of doing this (then going ahead and using parseFloat
, which doesn't really seem different). Interestingly isFinite
will get you the result you're after in almost all cases on its own (apart from whitespace strings, which for some reason return true
), so parseInt
vs parseFloat
seems irrelevant in this context. I certainly can't find a single input to that function where parseInt
makes a difference.
Number.isInteger()
? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Commented
Aug 13, 2019 at 3:55
isNumeric([0]) === true
and isNumeric(['123']) === true
Commented
Dec 12, 2019 at 20:11
This should help:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Very good link: Validate decimal numbers in JavaScript - IsNumeric()
function IsNumeric(val) {
return Number(parseFloat(val)) == val;
}
IsNumeric
was called with NaN
, but due to the quirk of NaN that it's not equal to anything it actually works out fine.
Number()
and rely on the double equals to do a bit of conversion: let isNumeric = (val) => parseFloat(val) == val;
Commented
Aug 31, 2016 at 11:40
Number(val).toString() == val.toString()
?
There is Javascript function isNaN which will do that.
isNaN(90)
=>false
so you can check numeric by
!isNaN(90)
=>true
var str = 'test343',
isNumeric = /^[-+]?(\d+|\d+\.\d*|\d*\.\d+)$/;
isNumeric.test(str);
false
against ' 1'
or '0x01'
, localization is not taken into account...
Commented
Jul 25, 2014 at 20:49
function isNumeric(str) { return /^\d*\.{0,1}\d*$/.test(str); }
isFinite(String(n)) returns true for n=0 or '0', '1.1' or 1.1,
but false for '1 dog' or '1,2,3,4', +- Infinity and any NaN values.
value => !isNan(+value)