简体   繁体   中英

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM