Emmanuel Akinfulubi

JavaScriptBasic

Integer division and remainder in JavaScript

Intermediate · 3 min read

137 minutes is 2 hours and 17 minutes. Working that out takes two answers from one division: how many whole times 60 fits into 137 (2), and what is left over (17). Programmers call these integer division and the remainder. You need them for clocks, countdown timers, splitting items into boxes, and anything that wraps round, like days of the week.

In this tutorial you will write divmod(a, b), which returns both answers, and floorDivMod(a, b), a version that behaves well with negative numbers. Negative numbers are where JavaScript's % operator surprises people. You need to know what a function and an array are.

The two halves of a division

JavaScript has no operator that gives a whole-number division. 137 / 60 gives a decimal, and you choose how to drop the fraction:

JavaScript

console.log(137 / 60);             // 2.283333333333333
console.log(Math.trunc(137 / 60)); // 2

Math.trunc cuts off the decimal part. The remainder has its own operator, %:

JavaScript

console.log(137 % 60); // 17

2 hours use up 120 minutes, and 17 are left.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

58 Integer division and remainder

fair

Split 137 minutes into hours and minutes. Then check what % does with a negative left-hand side, because it is not what most languages' documentation leads you to expect.

Stuck? Three hints, smallest first
  1. 1. There is no integer-division operator. Divide, then Math.trunc or Math.floor.
  2. 2. % in JavaScript is a remainder, not a mathematical modulo: it takes the sign of the left operand.
  3. 3. For a always-positive result use ((a % b) + b) % b.

Step 1: both answers in one function

Return the two answers together in an array, in the order "how many, what's left":

Step 1

const divmod = (a, b) => [Math.trunc(a / b), a % b];
const [hours, minutes] = divmod(137, 60);
console.log(hours, minutes); // 2 17

const [hours, minutes] = ... is destructuring: it unpacks the first item of the array into hours and the second into minutes.

Step 2: the sign of the remainder

Try a negative number on the left:

JavaScript

console.log(-7 % 3); // -1
console.log(7 % -3); // 1

In math class, "-7 mod 3" is 2. JavaScript's % gives -1. That is because % is a remainder, not a mathematical modulo, and its answer always takes the sign of the number on the left. In the second line the left side is positive, so the answer is positive, even though the right side is negative.

So divmod works out a negative division like this:

JavaScript

const divmod = (a, b) => [Math.trunc(a / b), a % b];
console.log(divmod(-17, 5)); // [ -3, -2 ]

-3 times 5 is -15, and -2 more makes -17. It is correct arithmetic, but a negative remainder is rarely what you want.

Step 3: why negatives matter: days of the week

Number the days 0 to 6, with Wednesday as 3. What day was 3 days before Wednesday? It should be Sunday, day 0. What about 4 days before? That is Saturday, day 6. With %:

JavaScript

console.log((3 - 4) % 7); // -1

There is no day -1. Wrapping backwards needs a remainder that is never negative. Every "previous" button on a carousel that won't go back past the first slide has this bug.

Step 4: a remainder that is never negative

The fix is a well-known pattern: take the remainder, add b, and take the remainder again.

JavaScript

console.log(((-1 % 7) + 7) % 7); // 6
console.log(((10 % 7) + 7) % 7); // 3

If the remainder was negative, adding 7 brings it into the range 0 to 6. If it was already positive, adding 7 goes too far, and the second % 7 brings it back.

To match, the whole-number part should use Math.floor, which always rounds down, instead of Math.trunc, which rounds towards zero. Then the two halves still fit together:

Step 4

const floorDivMod = (a, b) => [Math.floor(a / b), ((a % b) + b) % b];
console.log(floorDivMod(-17, 5));   // [ -4, 3 ]
console.log(floorDivMod(-1, 7)[1]); // 6
console.log(floorDivMod(-3, 7)[1]); // 4
console.log(floorDivMod(17, 5));    // [ 3, 2 ]

-4 times 5 is -20, and 3 more makes -17. The last line shows that for positive numbers both versions agree.

The full solution

The answer panel has divmod and floorDivMod, splits 137 minutes, compares both versions on -17 and 5, and wraps a negative day number into the range 0 to 6. Press Run to see the output.

The answer

// Truncating pair: matches the sign of the input, like C.
const divmod = (a, b) => [Math.trunc(a / b), a % b];

// Flooring pair: the remainder is never negative, which is what clock and
// calendar arithmetic wants.
const floorDivMod = (a, b) => [Math.floor(a / b), ((a % b) + b) % b];

console.log('137 minutes ->', divmod(137, 60), '(hours, minutes)');
console.log('-17 / 5 truncating ->', divmod(-17, 5));
console.log('-17 / 5 flooring   ->', floorDivMod(-17, 5));
console.log('-7 % 3 ->', -7 % 3, '  7 % -3 ->', 7 % -3);
console.log('3 days before Wednesday (day 3) ->', floorDivMod(3 - 3 - 3, 7)[1]);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('137 minutes is 2 hours 17', divmod(137, 60), [2, 17]);
test('the remainder takes the sign of the LEFT operand', -7 % 3, -1);
test('so a negative left side gives a negative remainder', 7 % -3, 1);
test('truncating division of a negative', divmod(-17, 5), [-3, -2]);
test('flooring division of the same numbers differs in both halves', floorDivMod(-17, 5), [-4, 3]);
test('the flooring remainder is never negative', floorDivMod(-1, 7)[1], 6);
test('which is what makes day-of-week arithmetic work backwards', floorDivMod(-3, 7)[1], 4);
test('and both agree for positives', [divmod(17, 5), floorDivMod(17, 5)], [[3, 2], [3, 2]]);

% is a remainder operator, so its sign follows the dividend: -7 % 3 is -1, not the 2 that a mathematician means by "−7 mod 3". Every wrapping bug — a day-of-week index, a carousel that will not scroll left, an angle that goes negative — is this line.

((a % b) + b) % b is the fix worth memorising: it is a modulo that always lands in 0..b-1. And since there is no integer-division operator, pick trunc or floor deliberately; as exercise 52 showed, they part company the instant a negative appears.

Common mistakes

  • Treating % as a true modulo. -7 % 3 is -1 in JavaScript. For wrap-around code, use ((a % b) + b) % b.
  • Mixing trunc and floor. For positive numbers they agree. For negatives they differ by one, so pick the one that matches your remainder.
  • Using parseInt(a / b) to drop decimals. It turns the number into text first, and very small or very large numbers written with an e give wrong answers. Use Math.trunc or Math.floor.

Try it yourself

  1. Turn 4,000 seconds into hours, minutes and seconds.
  2. Write dayBefore(day, n) that goes back n days from day (0 to 6) and always lands in 0 to 6.
  3. Pack 50 eggs into trays of 12: how many full trays, and how many eggs are left?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.