Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
25
rated 0 times [  28] [ 3]  / answers: 1 / hits: 27726  / 16 Years ago, sun, march 1, 2009, 12:00:00

In PHP, it's pretty easy:



is_numeric(23);//true
is_numeric(23);//true
is_numeric(23.5);//true
is_numeric(true);//false


But how do I do this in Javascript?
I could use a regular expression, but is there a function for this?


More From » javascript

 Answers
42

What about:



function isNumber(n){
return typeof(n) != boolean && !isNaN(n);
}


The isNaN built-in function is used to check if a value is not a number.



Update: Christoph is right, in JavaScript Boolean types are convertible to Number, returning the 1 for true and 0 for false, so if you evaluate 1 + true the result will be 2.



Considering this behavior I've updated the function to prevent converting boolean values to its numeric representation.


[#99906] Wednesday, February 25, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dequant

Total Points: 88
Total Questions: 99
Total Answers: 95

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
dequant questions
;