JavaScript(JS) JS check if a number is float or integer

In JavaScript, you can use the Number.isInteger() method to check if a number is an integer or not. If the number is an integer, this method will return true; otherwise, it will return false.

To check if a number is a float, you can subtract the integer value of the number from the number itself and check if the result is not equal to zero. If the result is not equal to zero, then the number is a float.

Here's an example that demonstrates how to check if a number is an integer or a float:

const num1 = 42;        // integer
const num2 = 3.14;      // float

console.log(Number.isInteger(num1));  // true
console.log(Number.isInteger(num2));  // false

if (num1 % 1 === 0) {
  console.log(`${num1} is an integer`);
} else {
  console.log(`${num1} is a float`);
}

if (num2 % 1 === 0) {
  console.log(`${num2} is an integer`);
} else {
  console.log(`${num2} is a float`);
}
S‮o‬urce:www.theitroad.com

In this example, we first use the Number.isInteger() method to check if num1 is an integer or not. Since num1 is an integer, the method returns true. However, since num2 is a float, the method returns false.

Next, we use the modulo operator (%) to check if the remainder when dividing the number by 1 is equal to zero. If the remainder is zero, then the number is an integer. If not, then the number is a float.