views:

361

answers:

8

Hello, what seems to be a simple question turns out as a difficult task to me. I need this:

if (number == integer) 

if (1.589 == integer) // false
if (2 == integer) // true

Any clues?

+16  A: 
num % 1 === 0

This will convert num to type Number first, so any value which can be converted to an integer will pass the test (e.g. '42', true).

If you want to exclude these, additionally check for

typeof num === 'number'

You could also use parseInt() to do this, ie

parseInt(num) == num

for an untyped check and

parseInt(num) === num

for a typed check.

Note that the tests are not equivalent: Checking via parseInt() will first convert to String, so eg true won't pass the check.

Also note that the untyped check via parseInt() will handle hexadecimal strings correctly, but will fail for octals (ie numeric strings with leading zero) as these are recognized by parseInt() but not by Number(). If you need to handle decimal strings with leading zeros, you'll have to specify the radix argument.

Christoph
This one does it, thank you.
jirkap
A: 

There is a javascript function called isNaN(val) which returns true if val is not a number.

If you want to use val as a number, you need to cast using parseInt() or parseFloat()

EDIT: oops. Corrected the error as mentioned in the comment

David
Just from the name of the function, I would think "isNaN" would return true if val "is *Not* a Number", which is what NaN stands for. Typo?
Matt Ball
isNaN(val) returns true if val is not a number, but it returns false for non-integer numbers as well so it won't solve the problem.
Amuck
+2  A: 

How about this:

if((typeof(no)=='number') && (no.toString().indexOf('.')==-1))
John Nolan
That won't work because 8.000 is still an integer.
Matt Ball
That probably depends on your definition (and use case) of integer
bdukes
Hmm. True. For inherently mathematical questions, I tend to think of them in terms of numbers and not numerals - hence, my comment above.
Matt Ball
A: 

you could either make use of javas parsing capabilities or as well try out the modulo operator %...

Gnark
+1  A: 

Would this not work:

if (parseInt(number, 10) == number)
{
  alert(number + " is an integer.");
}
paracycle
You should always include the radix parameter: parseInt(number, 10)
Greg
Oops, yes. Fixed it.
paracycle
@Greg: not necessarily - one might want hexadecimals to pass; octals will fail as they are recognized by `parseInt()` but not by `Number()`
Christoph
+6  A: 

Someone has already done it for you.

DanDan
As @Greg says above (http://stackoverflow.com/questions/1323314/detecting-if-a-given-number-is-an-integer#comment-1157013), this should include the radix parameter to parseInt.
bdukes
+3  A: 

if (Math.floor(x) == x)

Randy Proctor
+2  A: 

You could use the formal definition of integer:

Math.floor(x) === x