Reputation: 79
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
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
Reputation: 238
function isInteger(input){
Number.isInteger(input)
}
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
Upvotes: 1