Emmanuel Akinfulubi

JavaScriptMath

Integer division with trunc, floor and bitwise in JavaScript

Intermediate · 4 min read

Pagination, splitting minutes into hours, finding which row a grid cell sits in: all of these need integer division, a division that throws away the fraction and keeps the whole number. JavaScript has no integer division operator. 7 / 3 is 2.3333333333333335, and you have to drop the decimals yourself.

In this tutorial you will try four common ways to do that: Math.trunc, Math.floor, | 0 and >> 0. You will see where they agree, where they split on negative numbers, and where two of them return a completely wrong answer without a warning. You need to know % and arrow functions.

Two ways to drop a fraction

There are two sensible rules for turning 2.33 or -2.33 into a whole number:

  • Truncate: cut toward zero. 2.33 becomes 2 and -2.33 becomes -2.
  • Floor: always go down, toward minus infinity. 2.33 becomes 2, but -2.33 becomes -3.

For positive numbers they match. For negative numbers they differ by one. Neither is wrong, they are just two definitions.

What | 0 and >> 0 do

| (bitwise OR) and >> (shift right) work on the binary bits of a number. Before they do anything, JavaScript converts the number to a 32-bit signed integer: a whole number between -2147483648 and 2147483647. OR-ing with 0 or shifting by 0 changes no bits, so x | 0 just hands back that converted number. That conversion truncates, which is why people use it as a shortcut.

Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.

82 Integer division four ways, and where one of them lies

fair

Divide 7 by 3 and -7 by 3 using Math.trunc, Math.floor, | 0 and >> 0. Say which of the four pairs with % and which pairs with a true modulo, then find an input where the bitwise versions return the wrong answer.

Stuck? Three hints, smallest first
  1. 1. Math.trunc cuts towards zero; Math.floor always goes down.
  2. 2. Quotient times divisor plus remainder should give back the dividend. Try both quotients.
  3. 3. The bitwise operators convert their operand to a signed 32-bit integer first.

Step 1: four division helpers

Step 1

const idivTrunc = (a, b) => Math.trunc(a / b);
const idivFloor = (a, b) => Math.floor(a / b);
const idivBits = (a, b) => (a / b) | 0;
const idivShift = (a, b) => (a / b) >> 0;
console.log(idivTrunc(7, 3), idivFloor(7, 3), idivBits(7, 3), idivShift(7, 3)); // 2 2 2 2

Each one divides normally, then drops the fraction its own way. For 7 / 3 all four agree on 2.

Step 2: a negative dividend

Step 2

console.log(idivTrunc(-7, 3), idivFloor(-7, 3), idivBits(-7, 3), idivShift(-7, 3)); // -2 -3 -2 -2

-7 / 3 is about -2.33. Math.floor goes down to -3. The other three cut toward zero and stop at -2.

Step 3: pair each quotient with its remainder

A good integer division has a matching remainder, so that quotient times divisor plus remainder gives back the number you started with. That is a handy test.

Step 3

const mod = (a, n) => ((a % n) + n) % n;
console.log(idivTrunc(-7, 3) * 3 + (-7 % 3));  // -7
console.log(idivFloor(-7, 3) * 3 + mod(-7, 3)); // -7

% gives -1 for -7 and 3, and -2 * 3 + -1 is -7. So truncation goes with %. The mod function always lands between 0 and n - 1; it gives 2 here, and -3 * 3 + 2 is also -7. So floor goes with a true modulo.

The wrong turn is mixing them: idivFloor(-7, 3) * 3 + (-7 % 3) is -10. This is how off-by-one bugs get into date and paging code.

Step 4: minus zero

Step 4

console.log(Object.is(Math.trunc(-0.5), -0), Math.floor(-0.5)); // true -1

Math.trunc(-0.5) is minus zero, a special value that equals 0 with === but is still a separate value. Object.is is the comparison that can tell them apart. It rarely matters, but it is good to know it exists.

Step 5: where the bitwise versions lie

Now push past the 32-bit range.

Step 5

console.log(3000000000 | 0, Math.trunc(3000000000)); // -1294967296 3000000000
console.log(1e10 | 0);                               // 1410065408
console.log(NaN | 0, Infinity | 0);                  // 0 0

Three billion does not fit in 32 bits, so | 0 wraps it around to a negative number. Ten billion becomes 1410065408. And both NaN and Infinity, the values you most want to notice, quietly turn into 0.

Step 6: the honest range

Step 6

console.log(Math.trunc(2147483647.9) | 0); // 2147483647
console.log(2147483648 | 0);               // -2147483648

2147483647 is the largest 32-bit signed number, and it survives. One more and the value flips to the most negative one. So | 0 is only safe when you already know the number is inside that range. Math.trunc has no such limit.

The full solution

The answer panel has the four helpers and mod, and prints both divisions, the two quotient and remainder pairs, minus zero, and the large and junk values. Press Run to see the output.

The answer

const mod = (a, n) => ((a % n) + n) % n;

const idivTrunc = (a, b) => Math.trunc(a / b);
const idivFloor = (a, b) => Math.floor(a / b);
const idivBits = (a, b) => (a / b) | 0;
const idivShift = (a, b) => (a / b) >> 0;

console.log('7 / 3  :', idivTrunc(7, 3), idivFloor(7, 3), idivBits(7, 3), idivShift(7, 3));
console.log('-7 / 3 :', idivTrunc(-7, 3), idivFloor(-7, 3), idivBits(-7, 3), idivShift(-7, 3));
console.log('trunc pairs with %      :', idivTrunc(-7, 3) * 3 + (-7 % 3));
console.log('floor pairs with mod    :', idivFloor(-7, 3) * 3 + mod(-7, 3));
console.log('trunc(-0.5), floor(-0.5):', Math.trunc(-0.5), Math.floor(-0.5));
console.log('3000000000 | 0          :', 3000000000 | 0, 'against', Math.trunc(3000000000));
console.log('1e10 | 0                :', 1e10 | 0);
console.log('NaN | 0, Infinity | 0   :', NaN | 0, Infinity | 0);

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('for positives all four agree that 7 over 3 is 2', [idivTrunc(7, 3), idivFloor(7, 3), idivBits(7, 3), idivShift(7, 3)], [2, 2, 2, 2]);
test('for negatives floor goes down to -3 while the other three stop at -2', [idivTrunc(-7, 3), idivFloor(-7, 3), idivBits(-7, 3), idivShift(-7, 3)], [-2, -3, -2, -2]);
test('trunc is the partner of %: quotient times divisor plus remainder is -7', idivTrunc(-7, 3) * 3 + (-7 % 3), -7);
test('floor is the partner of the two-step mod, and reaches -7 the other way', idivFloor(-7, 3) * 3 + mod(-7, 3), -7);
test('Math.trunc(-0.5) is minus zero while Math.floor(-0.5) is -1', [Object.is(Math.trunc(-0.5), -0), Math.floor(-0.5)], [true, -1]);
test('| 0 folds anything past 32 bits, so three billion comes back negative', [3000000000 | 0, Math.trunc(3000000000)], [-1294967296, 3000000000]);
test('ten billion becomes 1410065408, with no warning at all', [1e10 | 0, Math.trunc(1e10)], [1410065408, 10000000000]);
test('| 0 also swallows NaN and Infinity, turning both into 0', [NaN | 0, Infinity | 0], [0, 0]);
test('so the bitwise trick is only honest inside the signed 32-bit range', [Math.trunc(2147483647.9) | 0, 2147483648 | 0], [2147483647, -2147483648]);

Four ways to divide and keep the whole part, and they split into two camps on negatives. Math.floor rounds towards minus infinity, so -7 / 3 is -3. The other three round towards zero and give -2. Neither is wrong; they are two different definitions of integer division, and each has its own matching remainder. Math.trunc goes with %, Math.floor goes with ((a % n) + n) % n. Mixing a floor quotient with a % remainder is how off-by-one bugs get into date and pagination code.

| 0 and >> 0 look like a free truncation and they are fast, but every bitwise operator in JavaScript first converts its operand to a signed 32-bit integer. Above 2147483647 the value wraps: three billion becomes -1294967296, ten billion becomes 1410065408, and nothing tells you. NaN | 0 and Infinity | 0 are both 0, so the trick also hides exactly the values you most want to catch. Use Math.trunc unless you have already proved the range.

Common mistakes

  • Using | 0 on big numbers. Anything past 2147483647 wraps to a wrong value. Use Math.trunc.
  • Mixing a floor quotient with a % remainder. They come from different rules, so for negatives they don't add back up. Pair floor with mod, and trunc with %.
  • Expecting NaN | 0 to stay NaN. It becomes 0, which hides bad input. Check with Number.isFinite first.

Try it yourself

  1. Convert 135 minutes to hours and minutes using idivTrunc and %. Then try -135. Which pair reads better for negatives?
  2. Write pageOf(index, perPage) that returns the page number (starting at 0) for an item index. Which helper should it use?
  3. Find the smallest positive whole number where n | 0 and Math.trunc(n) disagree.

Keep practising

Newsletter

New writing, when it lands.

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