Home >Web Front-end >JS Tutorial >How Can I Distinguish Between Floats and Integers in JavaScript?
Determining the Nature of a Number
In programming, it's often necessary to distinguish between float and integer numbers. A float represents a number with a decimal point, while an integer is a whole number without decimals.
Checking the Number Type
To check whether a given number is a float or an integer, one method is to examine the remainder when dividing it by 1. For a float, the remainder will not be zero, while for an integer, it will be zero. This can be implemented in JavaScript as follows:
function isInt(n) { return n % 1 === 0; }
However, if you are unsure whether the argument is a number, additional checks are required:
function isInt(n){ return Number(n) === n && n % 1 === 0; } function isFloat(n){ return Number(n) === n && n % 1 !== 0; }
ECMA Script 2015 Standard
In 2019, a standardized solution for checking number types was introduced in ECMA Script 2015:
Number.isInteger(n); // true if n is an integer
The above is the detailed content of How Can I Distinguish Between Floats and Integers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!