JavaScript - isInteger

javascript

// JavaScript - The isInteger problem:

ECMAscript 6 introduces a new Number.isInteger() function.  However, prior to 
ECMAScript 6, this is a bit more complicated, since no equivalent of the 
Number.isInteger() method is provided.

The issue is that, in the ECMAScript specification, integers only exist 
conceptually; i.e., numeric values are always stored as floating point values.

function isInteger(x) { return (x^0) === x; } 
function isInteger(x) { return Math.round(x) === x; }
function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); }

Do not use:
function isInteger(x) { return parseInt(x, 10) === x; }
While this parseInt-based approach will work well for many values of x, once x 
becomes quite large, it will fail to work properly. The problem is that 
parseInt() coerces its first parameter to a string before parsing digits. 
Therefore, once the number becomes sufficiently large, its string representation 
will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() 
will then try to parse 1e+21, but will stop parsing when it reaches the e 
character and will therefore return a value of 1.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License