How Do I Check That a Number Is Float or Integer?

When working with JavaScript, it is important to be able to determine whether a number is a float or an integer. While JavaScript does not have built-in methods to directly check the type of a number, there are several approaches you can take to achieve this.

1. Using the % (Modulus) Operator

One way to check if a number is an integer is by using the modulus operator (%). The modulus operator returns the remainder when one number is divided by another. If the remainder is 0, then the number is an integer; otherwise, it is a float.

function isIntegerUsingModulus(number) {
  return number % 1 === 0;
}

console.log(isIntegerUsingModulus(5)); // Output: true
console.log(isIntegerUsingModulus(5.5)); // Output: false

2. Using the Number.isInteger() Method

In ECMAScript 6 (ES6) and later versions, JavaScript introduced the Number.isInteger() method, which directly checks if a number is an integer.

function isIntegerUsingNumberIsInteger(number) {
  return Number.isInteger(number);
}

console.log(isIntegerUsingNumberIsInteger(5)); // Output: true
console.log(isIntegerUsingNumberIsInteger(5.5)); // Output: false

3. Using the Number.isSafeInteger() Method

If you want to check if a number is both an integer and within the safe integer range, you can use the Number.isSafeInteger() method. This method returns true if the number is an integer and can be safely represented as a JavaScript number; otherwise, it returns false.

function isSafeInteger(number) {
  return Number.isSafeInteger(number);
}

console.log(isSafeInteger(5)); // Output: true
console.log(isSafeInteger(9007199254740992)); // Output: false

Now that you have learned different ways to check if a number is a float or an integer, you can choose the method that best suits your needs. Remember to consider the compatibility of the method with the JavaScript version you are using in your project.

Happy coding!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *