DEV Community

Muhammad    Uzair
Muhammad Uzair

Posted on

How to check if Number is Float in JS

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 (3)

Collapse
jmitchell38488 profile image
Justin Mitchell • Edited on

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.

Collapse
t0nyba11 profile image
Tony B

I agree 99.9% :)

That is right in terms of storage, but it certainly has a 'concept' of integers - being any number with no decimal places. That's why the documentation to functions like parseInt tell you it returns an 'integer'. It is a concept in the language, but just a concept, used when doing bitwise operations or calling methods that strip the decimal places.

developer.mozilla.org/en-US/docs/W...

Collapse
bahree669 profile image
SaepulBahri

in Javascript you can use this :

/[\.]/.test(String(120.5))

Enter fullscreen mode Exit fullscreen mode