mathExpl
mathExpl

Reputation: 79

Is there a more efficient or generally better way to determine if a number is an integer than this?

Right now I'm using this function to determine if a number is an integer:

function isInteger(input){
    return (input%1==0);
}

is there a more efficient way to do this? I know there's a built in javascript function for this but it doesn't work in certain IE versions.

Upvotes: 1

Views: 88

Answers (3)

joews
joews

Reputation: 30330

According to jsPerf, ~~ (repeated bitwise NOT) and << 0 (shift left by 0 bits) are faster in my browser:

function isInteger(input) {
  return (~~input === input);
}

function isInteger2(input) {
  return (input << 0 === input);
}

WARNING: JavaScript bitwise operators coerce their operands to signed 32-bit integers, so this method is only safe for numbers up to Math.pow(2, 31) -1 (2147483647). Use another method if you can't guarantee that.

Of the other methods, n % 1 === 0 and Math.floor(value) === value are 40-50% slower and Number.isInteger is way behind.

However, they are all "pretty fast". Unless you have to check a lot of numbers, none of these methods are likely to be a bottleneck in your application.

Upvotes: 4

Yudhishthir Singh
Yudhishthir Singh

Reputation: 238

function isInteger(input){
    Number.isInteger(input)
}

Number.isInteger = Number.isInteger || function(value) {
  return typeof value === "number" && 
    isFinite(value) && 
    Math.floor(value) === value;
};

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

Upvotes: 1

VadimB
VadimB

Reputation: 5711

function isInt(val) {
    return val + 0 === val;
}

Upvotes: -2

Related Questions