« Back to home

JavaScript modulus weirdness

I just became aware of an interesting JavaScript ‘feature’. The code

y = x % 1;

is equivalent to

y = x - Math.floor(x);

because ECMA-262 says:

… the floating-point remainder r from a dividend n and a divisor d is defined by the mathematical relation r = n − (d * q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.

So if d is 1 then q is the largest integer that’s smaller than n/1, so r = n - Math.floor(n).

I will not be using this feature in my code.