0

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?

Community
  • 1
  • 1
Darwin Tech
  • 18,449
  • 38
  • 112
  • 187
  • this covers it pretty well: http://stackoverflow.com/questions/3885817/how-to-check-if-a-number-is-float-or-integer – Patrick Klug Nov 18 '12 at 23:11

4 Answers4

2

I haven't tested, but I'd suggest:

if (Math.round(x) == x) {
    // it's an integer
}

Simplistic JS Fiddle.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
0

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;
}
Community
  • 1
  • 1
David Müller
  • 5,291
  • 2
  • 29
  • 33
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!
Kenny Pyatt
  • 363
  • 1
  • 4
  • 17
0

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
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81