Handling Negative Values with the Remainder Operator
Overview
The remainder operator (%) returns the remainder after dividing one operand by another, always taking the sign of the dividend.
For a % b, where a is dividend and b is divisor, the result is always less than b and carries the same sign as a in JavaScript:
-7 % 3 // Result: -1 (remainder takes the sign of -7, the dividend)
7 % -3 // Result: 1 (remainder takes the sign of 7, the dividend)
-7 % -3 // Result: -1 (remainder takes the sign of -7, the dividend)
To convert negative results to positive ones, this function from The Coding Train on youtube provides a nice solution:
function modulo(dividend, divisor) {
return ((dividend % divisor) + divisor) % divisor;
}
How It Works
Case 1: Positive Dividend
dividend = 7, divisor = 3
7 % 3 = 11 + 3 = 44 % 3 = 1Result:1
Case 2: Negative Dividend
dividend = -7, divisor = 3
-7 % 3 = -1(JavaScript retains the dividend’s sign)-1 + 3 = 22 % 3 = 2Result:2
Summary
modulo(7, 3) = 1modulo(-7, 3) = 2