Tuesday, September 24, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Program to Check if a Number is Float or Integer

JavaScript Program to Check if a Number is Float or Integer

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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments