Check if a number has a decimal place/is a whole number
To determine if a number is a whole number or has a decimal place, use the modulo (%
) operator. If the operation returns a non-zero remainder, it's a decimal. Here's the code:
Deep dive into identifying decimal and whole numbers
Differentiating between decimal and whole numbers can be crucial for mathematical operations, validation, or formatting. Let's explore various methods and edge cases.
Modulo operator versatility
The num % 1
pattern determines whether a number is a whole number and extracts the decimal part. It even treats fixed decimal strings like 12.0
as integers!
Embracing Number.isInteger()
You can use Number.isInteger()
for an all-encompassing check. However, its lack of support in IE11 might turn off legacy browsers.
Tread safely with Number.isSafeInteger()
If the number could be astronomically big, use Number.isSafeInteger()
. It checks if values are within IEEE-754 double-precision limits.
String-based approach
Stringified numbers? Check for the absence of a decimal point. Remember, "100.00"
isn't a whole number.
Math.floor(num) == num
to the rescue
One more way to check for whole numbers – Math.floor(num) == num
. Old but gold.
Choose your method based on performance, readability, and compatibility, dear code ninja. Remember, num % 1
could be faster, while Number.isInteger(num)
can offer precision.
Navigating edge cases and special number landmines
JavaScript has special numeric values and edge cases begging your attention. Let's examine:
Dealing with NaN and Infinity
Handling NaN
and Infinity
requires special checks. Your trusty modulo operator might let you down here.
Jumbo numbers
__
For numbers beyond Number.MAX_SAFE_INTEGER
, JavaScript might start acting funny. Brace yourself and use BigInt or libraries like big.js for arbitrary precision.
Was this article helpful?