Explain Codes LogoExplain Codes Logo

How do I check that a number is float or integer?

javascript
number-check
type-detection
polyfill
Anton ShumikhinbyAnton Shumikhin·Aug 8, 2024
TLDR

Swift determination of whether a number is float or integer can be achieved as simple as this: check (num % 1) !== 0 for floats, or use Number.isInteger(num) for integers. Here's how to put them into action:

const num = 10.5; console.log(`Is float: ${ (num % 1) !== 0 }`); // true because 10.5 has a remainder console.log(`Is integer: ${ Number.isInteger(num) }`); // false because 10.5 isn't a whole number

Fundamentals of integers and floats

A precise understanding of what differentiates a float from an integer will build a solid foundation. An integer is a number without any decimal points—whole numbers, if you prefer. On the flip side, a float (or floating-point number) does have a decimal part—even if that decimal part is zero (e.g., 5.0).

Methods for distinguishing number types

JavaScript offers several methods to facilitate the distinction between integers and floats. Let's navigate through these, keeping an eye out for those pesky edge cases along the way.

Ensuring the value is numeric

Initially, it is crucial to verify if the given value is numeric. Here's one way of doing it:

function isValidNumber(value) { return Number(value) === value; }

Polyfill for Number.isInteger()

ES5 doesn't support Number.isInteger(). Talk about feeling left out! Hence, if you have to deal with an older browser (looking at you, IE), include this polyfill:

Number.isInteger = Number.isInteger || function(value) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; };

Give a hoot, don't pollute... with unsafe integers

JavaScript has a maximum safe integer (Number.MAX_SAFE_INTEGER). Going beyond that, precision takes a walk off a cliff leading to incorrect type checks—so keep it safe, folks!

Employing bitwise property

Bitwise operations can be used to verify integers. However, this superhero is not without a kryptonite—it falters beyond 32-bit integer range:

function isIntUsingBitwise(value) { return (value | 0) === value; }

parseInt() and equality

The parseInt() function along with the mighty equality operator can pinpoint integers:

function isParsedInt(value) { return parseInt(value, 10) === value; }

Watch out for false positives, though. parseInt can turn strings to integers, making "123abc" look like 123.

Integer string check with regex

Regex saves the day once again when dealing with integer strings:

const isIntRegex = /^-?\d+$/; console.log(isIntRegex.test("10")); // true, because we all know 10 doesn't float

Precautions to take

Being aware of JavaScript's quirks can save hours of debugging and keep you sane:

  • Is it finite? Just because isFinite() is old doesn't mean it's useless. You'll want to check finiteness before numeric type check.
  • Boundary check - think twice before flirting with JavaScript's Number.MIN_VALUE and Number.MAX_SAFE_INTEGER.
  • Negative integers - Yes, they're a thing. Check them right.
  • Strings that look like numbers: Convert them to number before type checking. A monkey in a spacesuit is still a monkey.

Bonus: Checking complex number types

The world of numbers is packed with variety. Here's how to tackle numbers in different forms.

Exponential notation

A number like 1e2 is an integer. But, it's wearing a "cool guys don't look at explosions" sunglasses. Give it a uniform before checking:

function isIntExponential(value) { return Number.isInteger(Number(value)); }

Checking hexadecimal and binary

JavaScript treats strings starting with 0x as hexadecimal and 0b as binary. Be a good host and parse them first:

const hex = "0xFF"; console.log(Number.isInteger(parseInt(hex, 16))); // true, hexadecimal numbers are people too

PHP parallels

If you're moonlighting as a PHP developer, the is_int(), is_float(), and ctype_digit() functions should feel right at home.

References