How to check if a Value is a Float in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 31, 2022

banner

Photo from Unsplash

Check if a Value is a Float in JavaScript #

To check if a value is a float:

  1. Check if the value has a type of number and is not an integer.
  2. Check if the value is not NaN.
  3. If a value is a number, is not NaN and is not an integer, then it's a float.
index.js
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

We first check if the provided value has a type of number. If it doesn't we return false straight away.

We used the logical AND (&&) operator to check for multiple conditions. For our if block to run, all conditions have to be met.

The second condition checks that the provided value isn't NaN (not a number). Unfortunately, NaN has a type of number in JavaScript.

index.js
console.log(typeof Number.NaN); // 👉️ number
We have to do the NaN check because NaN has a type of number and isn't an integer.

If the provided value is of type number, is not NaN and is not 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 that can be represented as an integer.

index.js
console.log(Number.isInteger(10.0)); // 👉️ true

It depends on your use case whether you consider 10.0 to be an integer or float.

Our implementation of the function considers numbers like 1.0 and 5.0 to not be floats.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.