Check if a variable contains a numerical value in Javascript?
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.
I don't think any of the suggestions till now actually work. Eg
!isNaN(parseFloat(foo))
doesn't because parseFloat()
ignores trailing non-numeric characters.
To work around this, you could compare the returned value to the one returned by a cast via Number()
(or equivalently by using unary +
, but I prefer explicit casting):
parseFloat(foo) === Number(foo)
This will still work if both functions return NaN
because NaN !== NaN
is true
.
Another possibility would be to first cast to string, then to number and then check for NaN
, ie
!isNaN(Number(String(foo)))
or equivalently, but less readable (but most likely faster)
!isNaN(+('' + foo))
If you want to exclude infinity values, use isFinite()
instead of !isNaN()
, ie
isFinite(Number(String(foo)))
The explicit cast via Number()
is actually unnecessary, because isNan()
and isFinite()
cast to number implicitly - that's the reason why !isNaN()
doesn't work!
In my opinion, the most appropriate solution therefore would be
isFinite(String(foo))
As Matthew pointed out, the second approach does not handle strings that only contain whitespace correctly.
It's not hard to fix - use the code from Matthew's comment or
isFinite(String(foo).trim() || NaN)
You'll have to decide if that's still nicer than comparing the results of parseFloat()
and Number()
.