![]() |
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. Table of ContentWe will explore every approach to Check if a Number is a Float or Integer, along with understanding their basic implementations. Using the Number.isInteger() MethodThe 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. SyntaxNumber.isInteger(number);
Example: This example uses the Number.isInteger() Method to check the Number. Javascript
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
Output
Is 3.14 a integer? false Using Regular ExpressionsThis 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
Output
Is 123.456 a float? true |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |