Is there any simple method in JavaScript / jQuery to check whether the variable is a number or not (preferably without a plugin)? I want to alert whether the variable is a number or not.
Thanks in advance...:)
I wouldn't recommend the isNaN
function to detect numbers, because of the Java Script type coercion.
Ex:
isNaN(""); // returns false (is number), a empty string == 0
isNaN(true); // returns false (is number), boolean true == 1
isNaN(false); // returns false (is number), boolean false == zero
isNaN(new Date); // returns false (is number)
isNaN(null); // returns false (is number), null == 0 !!
You should also bear in mind that isNaN
will return false (is number) for floating point numbers.
isNaN('1e1'); // is number
isNaN('1e-1'); // is number
I would recommend to use this function instead:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With