Method 1: Using Number.isInteger() Function
This is the most straightforward method to check if a number is an integer. The Number.isInteger() method returns a boolean value indicating whether the provided value is an integer.
javascriptfunction checkNumberType(num) { if (Number.isInteger(num)) { return `${num} is an integer`; } else { return `${num} is a float`; } } console.log(checkNumberType(10)); // Output: 10 is an integer console.log(checkNumberType(10.5)); // Output: 10.5 is a float
Method 2: Using the Modulo Operator %
Another approach is to use the modulo operator %. If the remainder when dividing the number by 1 is zero, it is an integer; otherwise, it is a float.
javascriptfunction checkNumberType(num) { if (num % 1 === 0) { return `${num} is an integer`; } else { return `${num} is a float`; } } console.log(checkNumberType(10)); // Output: 10 is an integer console.log(checkNumberType(10.1)); // Output: 10.1 is a float
Method 3: Using Math.floor() or Math.ceil() Methods
By comparing the number with its floor or ceiling value. If both are equal, it is an integer; otherwise, it is a float.
javascriptfunction checkNumberType(num) { if (Math.floor(num) === num) { return `${num} is an integer`; } else { return `${num} is a float`; } } console.log(checkNumberType(12)); // Output: 12 is an integer console.log(checkNumberType(12.3)); // Output: 12.3 is a float
Summary
The following are several common methods in JavaScript for checking if a number is an integer. Number.isInteger() is the most concise and modern approach, and is generally recommended. However, other methods like using % or Math.floor() can be useful in specific scenarios, particularly when compatibility is a concern.