DEV Community

loading...

How to check if Number is Float in JS

uzairsamad profile image Muhammad Uzair ・1 min read

Usually we check types in javascript by using typeOf method but javascript doesn't support float type so it return a Number when you check a type of float number.
Like: typeOf(4.56) = Number

How to check if number is float or not in JS:

   function isFloat(n){
      return Number(n) === n && n % 1 !== 0;
    }

Explanation:
If the mod of a number divided by 1 is not equal to zero then it must a float number.

Discussion (1)

pic
Editor guide
Collapse
jmitchell38488 profile image
Justin Mitchell

This doesn't validate if the specific type is a float. In fact, JS has no concept of floats, it only has the singular concept of number, so what you're really testing here is if the value is an whole number (int) or a decimal (double).

All JS numbers are doubles; 64 bit double precision floating point numbers.