Check if a variable is an integer or a float in JavaScript.

Check if a variable is an integer or a float in JavaScript.

At the time of writing this post ES6 is not widely available on all browsers. So the purpose of this post, is to find a reliable solution to check if the variable is an integer or a float in ES5.

Unlike in other languages, integers and floats are not native data types in JavaScript. For both these types JavaScript assigns Number as it's common datatype.

Integer

We can find if a variable is an integer or not by using ES6's Number.isInteger() method. But that's just available only in ES6.

The more reliable two methods to check for an Integer in ES5 are,

Please go ahead and pick one and leave the worry to the isInt() method that we made.

Float πŸŠβ€β™€οΈ

Unlike ES6's Number.isInteger() method to check for Integers, we have nothing of that sort for float.

This forces us to make our custom method.

Both isInt() and isFloat() gives you a solid way to check for integer and float in JavaScript which doesn't require any compiler like Babel.

You can make it even more robust by replacing the typeof num === 'number' and isFinite(num) conditions with typeOf() and isInfinity() methods that we made on our previous posts. You can find the links below.

Reliable way to check datatypes in JavaScript
Many versions have come & gone, but this one liner is always a winner πŸ†!
JavaScript: Infinity War
Don’t get too excited. We are not showing Avengers: Infinity War
Show Comments