Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a given number is an integer?

How can I test a variable to ascertain if it contains a number, and it is an integer?

e.g.

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

Any clues?

like image 953
jirkap Avatar asked Aug 24 '09 16:08

jirkap


1 Answers

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.

like image 76
Christoph Avatar answered Oct 01 '22 03:10

Christoph