Testing for Integers with the Modulo Operator
The modulo operator, %, gives the remainder when one number is divided by another. All integers give a remainder of 0 when divided by 1.
Listing 1
var num1 = 3, num2 = 5.2;
alert(num1 % 1); // 0
alert(num2 % 1); // 0.2
As 0 is falsey and any other number is truthy, num % 1 can be read as 'num is not an integer' and will give true or false in a boolean test.
Listing 2
function isInteger(num){
return num % 1 ? "Not an integer" : "Integer";
}
alert(isInteger(3)); // Integer
alert(isInteger(5.2)); // Not an integer
