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
To check types in javascript you can use the typeof operator:
js> var x = 1;
js> typeof(x);
number
So:
if (typeof(x) === 'number') {
// Do something
}
If you want to coerce the value of a variable to an integer, you can use parseInt(x, 10) which will parse the value as an integer in base 10. Similarly, you can use parseFloat if you want a floating point value. However, these will always coerce regardless of type so passing null, true, etc will always return a number. However, you can check whether its a valid number by calling isNaN.
So, putting it all together:
!isNaN(parseFloat(23)) // true
!isNaN(parseFloat('23')) // true
!isNaN(parseFloat(23.5)) // true
!isNaN(parseFloat(true)) // false
or
function isNumber(x) {
return !isNaN(parseFloat(x));
}