Checking for Decimals in JavaScript
Checking for decimals is useful for displaying formatted numbers and other checks. Although doing so is not obvious in JS. The key is the % operator:
const hasDecimals = function(number) { return number % 1 !== 0; } console.log(hasDecimals(5.22)); // true console.log(hasDecimals(41.00001)); // true console.log(hasDecimals(0)); // false console.log(hasDecimals(42)); // false
The % returns the remainder of Euclidean division (although there is a slight difference in JS). Basically, the first operand is continually subtracted by the second as long as the number keeps the same negative/positive value. If there is anything left, that is the remainder
For example, 5 % 2 = 1, since 5 - 2 = 3, then 3 - 2 = 1. So 5.22 % 2 = 1.22 = 5.22 - 2 = 3.22 - 2 = 1.22. Finally, by using 1 as the second operator instead, it means that only integers will have 0 left after subtractions.
By including an isNaN check, the above can be used to filter out other types (Something that a string conversion decimal check could not easily do):
const hasDecimals2 = function(number) { const result = number % 1; return !isNaN(result) && result !== 0; } console.log(hasDecimals2(null)); // false console.log(hasDecimals2(undefined)); // false console.log(hasDecimals2({})); // false console.log(hasDecimals2('test')); // false console.log(hasDecimals2(2.22)); // true console.log(hasDecimals2(new Number(2.22))); // true
Note that typeof is not used since it gives 'object' when new Number() is used.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/hasDecimals.js














