How to check if a Value is a Float in JavaScript


Borislav Hadzhiev

Sat Oct 16 20212 min read


Photo by Marcos Moraes

Check if a Value is a Float in JavaScript #

To check if a value is a float:

  1. Check that the value has a type of number and is not an integer.
  2. You can check whether a value is not an integer, by using the logical NOT (!) operator before the call to the Number.isInteger() method.
  3. If a value is a number, it's not 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
We have to do the 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:

  • is an integer
  • is a float that can be represented as an integer

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.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee