user2033475
user2033475

Reputation:

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?

Upvotes: 30

Views: 20287

Answers (7)

polo-language
polo-language

Reputation: 846

Can use the function Number.isInteger(). It also takes care of checking that the value is a number.

For example:

Number.isInteger(3)     // true
Number.isInteger(3.1)   // false
Number.isInteger('3')   // false

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger

Upvotes: 3

Randy Proctor
Randy Proctor

Reputation: 7544

This works:

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

Upvotes: 11

David
David

Reputation: 5456

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

Upvotes: -1

Christoph
Christoph

Reputation: 169533

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.

Upvotes: 62

paracycle
paracycle

Reputation: 7850

Would this not work:

if (parseInt(number, 10) == number)
{
  alert(number + " is an integer.");
}

Upvotes: 2

Malvolio
Malvolio

Reputation:

You could use the formal definition of integer:

Math.floor(x) === x

Upvotes: 5

Johnno Nolan
Johnno Nolan

Reputation: 29659

How about this:

if((typeof(no)=='number') && (no.toString().indexOf('.')==-1))

Upvotes: 2

Related Questions