Skip to content

Handling negative values with remainder operator

Posted on:January 1, 2025 at 05:31 PM

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

  1. 7 % 3 = 1
  2. 1 + 3 = 4
  3. 4 % 3 = 1 Result: 1

Case 2: Negative Dividend

dividend = -7, divisor = 3

  1. -7 % 3 = -1 (JavaScript retains the dividend’s sign)
  2. -1 + 3 = 2
  3. 2 % 3 = 2 Result: 2

Summary