Open In App

JavaScript Program to Check if a Number is Float or Integer

Last Updated : 04 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to check whether a number is a float or an integer in JavaScript. A float is a number with a decimal point, while an integer is a whole number or a natural number without having a decimal point.

We will explore every approach to Check if a Number is a Float or Integer, along with understanding their basic implementations.

Using the Number.isInteger() Method

The Number.isInteger() Method checks if the given number is an integer or not. It returns true if the number is an integer, and false if it’s a float or not a number at all.

Syntax

Number.isInteger(number);

Example: This example uses the Number.isInteger() Method to check the Number.

Javascript




const inputNumber = 42;
const isInteger =
    Number.isInteger(inputNumber);
console.log(
    `Is ${inputNumber} an integer? ${isInteger}`
);


Output

Is 42 an integer? true

Using the Modulus Operator (%)

The Modulus Operator calculates the remainder when the number is divided by 1. If the remainder is 0, the number is an integer; otherwise, it’s a float.

Syntax

(number % 1 === 0);

Example: This example uses the Modulus Operator (%) to check the Number.

Javascript




const inputNumber = 3.14;
const isInteger = inputNumber % 1 === 0;
console.log(
    `Is ${inputNumber} a integer? ${isInteger}`
);


Output

Is 3.14 a integer? false

Using Regular Expressions

This approach involves converting the number to a string and using a Regular Expression to check if it contains a decimal point. If it does, it’s a float; otherwise, it’s an integer.

Syntax

/\d+\.\d+/.test(numberString);

Javascript




const inputNumber = 123.456;
const numberString = inputNumber.toString();
const isFloat = /\d+\.\d+/.test(
    numberString
);
console.log(
    `Is ${inputNumber} a float? ${isFloat}`
);


Output

Is 123.456 a float? true


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads