javascriptinteger

how many ways to check if x is integer and which one is most efficient?


I already checked what is the best way to check variable type in javascript question on So but didn't found answer of my question.

In javascript how many ways to find if input type is integer? which one is efficient?

I was looking the way to find the integer in javascript and found number of ways to do this:

  1. Using typeof

function isInteger(x) 
{ 
   return (typeof x === 'number') && (x % 1 === 0); 
   
}
console.log(isInteger(10));
console.log(isInteger(10.1))

  1. Using parseInt

function isInteger(x) 
{ 
   return parseInt(x, 10) === x; 
   
}
console.log(isInteger(10));
console.log(isInteger(10.1));

  1. Using Math.round

function isInteger(x)
{ 
  return Math.round(x) === x; 
  
}
console.log(isInteger(10));
console.log(isInteger(10.1));

Is there any other way to find the type of Integer and which one will be most efficient for consider small to large integer values.


Solution

  • I am concluding answer for this question after some resarch

    From ECMAscript 6 which introduces a new Number.isInteger() function for precisely this purpose.

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

    The simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following use of the bitwise XOR operator:

    function isInteger(x) 
    { 
      return (x ^ 0) === x; 
    } 
    

    Others like Math.round() ,typeof and parseInt can be used also to find the Integer.

    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.