Possible Duplicate:
How to check if a number is float or integer?
What is the bet way to check that a variable is an integer?
in Python you can do:
if type(x) == int
Is there an equally elegant equivalent in JS?
Possible Duplicate:
How to check if a number is float or integer?
What is the bet way to check that a variable is an integer?
in Python you can do:
if type(x) == int
Is there an equally elegant equivalent in JS?
I haven't tested, but I'd suggest:
if (Math.round(x) == x) {
// it's an integer
}
Use isNaN (is not a number - but beware that the logic is negated) and combine with parseInt:
function is_int(x)
{
return (!isNaN(x) && parseInt(x) == x)
}
As suggested here, the following will also do:
function isInt(n) {
return n % 1 === 0;
}
Javascript offers typeof
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/typeof
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number(1) === 'number'; // but never use this form!
The numeric value of an integer's parseFloat() and parseInt() equivalents will be the same. Thus you can do like so:
function isInt(value){
return (parseFloat(value) == parseInt(value)) && !isNaN(value);
}
Then
if (isInt(x)) // do work