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
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
Number.isInteger(42.0); //=> true
The same as above holds up when the precision limit of floats is exceeded, therefore the following evaluates to
Number.isInteger(42.000000000000001); //=> true
But with one less zero it evaluates to
Number.isInteger(42.00000000000001); //=> false