Technical skill practice

JavaScript Integer Division: Math.floor vs Math.trunc

JavaScript Number division produces a numeric quotient. If you need an integer result, define whether to round downward or discard the fraction toward zero. Math.floor and Math.trunc differ for negative values.

The task

Divide seven and negative seven by three, then compare both policies. Treat division by zero separately rather than forcing it into an integer result.

Runnable Node 22 example

const assert = require('node:assert/strict');

assert.equal(Math.floor(7 / 3), 2);
assert.equal(Math.trunc(7 / 3), 2);
assert.equal(Math.floor(-7 / 3), -3);
assert.equal(Math.trunc(-7 / 3), -2);
assert.equal(7 / 0, Infinity);
assert.equal(Number.isFinite(7 / 0), false);
console.log(`positive=${Math.floor(7 / 3)}; negativeFloor=${Math.floor(-7 / 3)}; negativeTrunc=${Math.trunc(-7 / 3)}`);

Expected output and explanation

Both methods give two for the positive quotient. For the negative quotient, downward rounding reaches negative three, while truncation removes the fractional part and reaches negative two. An application that permits negative inputs cannot choose between these policies from positive tests alone.

The zero-divisor assertions expose a nonfinite result rather than an exception. A wrapper requiring a finite integer should reject that input explicitly. This example uses ordinary Numbers; BigInt division has a different type contract and should not be silently mixed into the same operation.

Output from the example

positive=2; negativeFloor=-3; negativeTrunc=-2

Pitfall to check

Bitwise shortcuts coerce values into limited-width integer behavior and can corrupt larger values. Use the operation that expresses the rounding rule, plus appropriate bounds, instead of assuming a terse shortcut preserves every Number.

Questions, answered

Which result should I use for page counts?

Define the rule first. Rounding a count upward to allocate a partial final page is a different requirement from either downward floor or truncating a signed quotient.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.