Borislav Hadzhiev
Sat Oct 16 2021·2 min read
Photo by Marcos Moraes
To check if a value is a float:
Number.isInteger()
method.NaN
and it's not an integer, then it's a
float.function isFloat(value) { if ( typeof value === 'number' && !Number.isNaN(value) && !Number.isInteger(value) ) { return true; } return false; } console.log(isFloat(1)); // 👉️ false console.log(isFloat(1.5)); // 👉️ true console.log(isFloat(-1.5)); // 👉️ true console.log(isFloat('1.5')); // 👉️ false
In our if
statement, we first check if the passed in value has a type of
number. If it doesn't we return false
straight away.
We use the
logical AND (&&)
operator to chain multiple conditions. For our if
block to run, all conditions
have to be met.
Our second condition is that the provided value is not NaN
(not a number).
Funnily enough NaN
has a type of number
in JavaScript.
console.log(typeof Number.NaN); // 👉️ number
NaN
check because NaN
has a type of number
and it's not an integer.If the passed in value is of type number
, it's not NaN
and it isn't an
integer, we return true
.
There is a catch when using the Number.isInteger method.
It returns true
if the passed in value:
Here's an example of a float tha can be represented as an integer.
console.log(Number.isInteger(10.0)); // 👉️ true
It depends on your use case whether you consider 10.0
to be an integer or
float.
In the way we wrote the function it considers numbers like 1.0
and 5.0
to
not be floats.