Join my Laravel for REST API's course on Udemy 👀

Check if a number is an integer in JavaScript

July 11, 2022  ‐ 1 min read

In certain cases you need to check whether the number that is passed as an argument or so is an integer.

For such a use-case we use the method Number.isInteger(). Which returns true if the number is an integer and false otherwise.

Number.isInteger(42);
//=> true

Seems pretty straight forward but there are a couple gotchas to be aware of.

This one is probably as expected but integers as a string evaluate to false. If you are expecting an integer from a form field you should parse it first to an integer.

Number.isInteger('42');
//=> false

Floating-point looking values which represent an integer evaluate to true:

Number.isInteger(42.0);
//=> true

The same as above holds up when the precision limit of floats is exceeded, therefore the following evaluates to true:

Number.isInteger(42.000000000000001);
//=> true

But with one less zero it evaluates to false:

Number.isInteger(42.00000000000001);
//=> false