Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  137] [ 2]  / answers: 1 / hits: 20302  / 13 Years ago, thu, april 14, 2011, 12:00:00

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...:)


More From » jquery

 Answers
9

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);
}

[#92728] Wednesday, April 13, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cadendericki

Total Points: 482
Total Questions: 109
Total Answers: 103

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
cadendericki questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Wed, Jul 8, 20, 00:00, 4 Years ago
Thu, May 14, 20, 00:00, 4 Years ago
;