Sub topic 11
Rounding: round, floor, ceil, and trunc
This chapter assumes you know how JavaScript stores numbers as 64-bit floats, why 0.1 + 0.2 is not exactly 0.3, and how -0 and NaN behave. Those topics come from earlier chapters. Here you will learn the four basic ways to turn a fractional number into an integer, where each one surprises people, and how to round to a fixed number of decimal places without getting caught by binary representation errors.
The four functions at a glance
Each function answers a different question about which integer to pick:
Math.floor(x)returns the largest integer less than or equal tox. It rounds toward negative infinity.Math.ceil(x)returns the smallest integer greater than or equal tox. It rounds toward positive infinity.Math.trunc(x)removes the fractional part. It rounds toward zero.Math.round(x)returns the nearest integer. Whenxsits exactly halfway between two integers, it rounds toward positive infinity.
For positive numbers, floor and trunc agree. For negative numbers, they don't, and that difference causes most rounding bugs.
| x | Math.round | Math.floor | Math.ceil | Math.trunc |
|---|---|---|---|---|
| 2.4 | 2 | 2 | 3 | 2 |
| 2.5 | 3 | 2 | 3 | 2 |
| 2.6 | 3 | 2 | 3 | 2 |
| -2.4 | -2 | -3 | -2 | -2 |
| -2.5 | -2 | -3 | -2 | -2 |
| -2.6 | -3 | -3 | -2 | -2 |
| -0.4 | -0 | -1 | -0 | -0 |
const samples = [2.4, 2.5, 2.6, -2.4, -2.5, -2.6, -0.4];
for (const x of samples) {
console.log(
x,
Math.round(x),
Math.floor(x),
Math.ceil(x),
Math.trunc(x)
);
}Math.round and the half-up rule
Many people learn in school that 2.5 rounds to 3 and -2.5 rounds to -3. This is called "round half away from zero." Math.round does something else. It rounds ties toward positive infinity, so -2.5 becomes -2.
console.log(Math.round(2.5)); // 3
console.log(Math.round(-2.5)); // -2
console.log(Math.round(-2.51)); // -3
console.log(Math.round(0.5)); // 1
console.log(Math.round(-0.5)); // -0This asymmetry matters whenever you round values that can be negative, such as temperature deltas, account adjustments, or coordinates. If your domain expects symmetric behavior, build it from Math.abs and Math.sign:
function roundHalfAwayFromZero(x) {
return Math.sign(x) * Math.round(Math.abs(x));
}
console.log(roundHalfAwayFromZero(2.5)); // 3
console.log(roundHalfAwayFromZero(-2.5)); // -3
console.log(roundHalfAwayFromZero(-2.4)); // -2Banker's rounding
Finance and statistics often use "round half to even" (also called banker's rounding). Ties go to the nearest even integer, so repeated rounding doesn't drift upward on average. JavaScript has no built-in function for it, but you can build one on top of Math.round:
function roundHalfEven(x) {
const r = Math.round(x);
const isTie = Math.abs(x % 1) === 0.5;
return isTie && r % 2 !== 0 ? r - 1 : r;
}
console.log(roundHalfEven(0.5)); // 0
console.log(roundHalfEven(1.5)); // 2
console.log(roundHalfEven(2.5)); // 2
console.log(roundHalfEven(-2.5)); // -2
console.log(roundHalfEven(-3.5)); // -4The function works because Math.round always pushes ties upward. When the result of a tie is odd, stepping down by one lands on the even neighbor.
floor versus trunc for negative numbers
Use Math.trunc when you want "the integer part," as in C-style integer division. Use Math.floor when you want a consistent downward step, as in bucketing values into ranges.
// Integer division that rounds toward zero
console.log(Math.trunc(-7 / 2)); // -3
console.log(Math.floor(-7 / 2)); // -4
// Bucketing: which 10-unit bin does a value fall into?
function bin(value, size) {
return Math.floor(value / size);
}
console.log(bin(15, 10)); // 1
console.log(bin(-5, 10)); // -1 (trunc would wrongly give -0, same bin as 5)If you used trunc for bucketing, the values -9.9 through 9.9 would all land in bin 0. That bin would be twice as wide as every other bin.
Math.ceil for counting
Math.ceil fits cases where a partial unit still needs a whole one, such as pages, boxes, or batches.
function pageCount(totalItems, perPage) {
return Math.ceil(totalItems / perPage);
}
console.log(pageCount(95, 10)); // 10
console.log(pageCount(100, 10)); // 10
console.log(pageCount(0, 10)); // 0Signed zero in results
Several of these functions return -0 for small negative inputs: Math.round(-0.4), Math.ceil(-0.5), and Math.trunc(-0.9) all produce -0. -0 === 0 is true, so comparisons still work. The sign shows up in Object.is, in 1 / x, and in some display code. String(-0) gives "0", but (-0).toLocaleString() returns "-0" in modern engines. If a stray minus sign in a UI would confuse users, normalize it:
const r = Math.round(-0.4);
console.log(Object.is(r, -0)); // true
const clean = r + 0; // -0 + 0 is +0
console.log(Object.is(clean, 0)); // trueRounding to decimal places
None of the four functions accepts a "number of digits" argument. The common workaround is to scale, round, and scale back:
console.log(Math.round(1.2345 * 100) / 100); // 1.23
console.log(Math.round(1.005 * 100) / 100); // 1 (expected 1.01)The second line fails because 1.005 is stored as about 1.00499999999999989. Multiplying by 100 gives 100.49999999999999, which rounds down. The scaling step itself adds binary error.
A more reliable approach shifts the decimal point through exponent notation in a string. The string "1.005e2" parses directly to the double closest to 100.5, and 100.5 is exactly representable:
function roundTo(value, places) {
const [mantissa, exp = "0"] = String(value).split("e");
const shifted = Math.round(Number(`${mantissa}e${Number(exp) + places}`));
const [m2, e2 = "0"] = String(shifted).split("e");
return Number(`${m2}e${Number(e2) - places}`);
}
console.log(roundTo(1.005, 2)); // 1.01
console.log(roundTo(1.2345, 2)); // 1.23
console.log(roundTo(1e-7, 8)); // 1e-7
console.log(roundTo(1234.5, -2)); // 1200Splitting on "e" handles inputs that String already prints in exponent form, such as 1e-7. A naive version would build "1e-7e8", which parses to NaN. A negative places value rounds to tens, hundreds, and so on. Behind the scenes, roundTo still uses Math.round, so negative ties still round toward positive infinity. To change that, swap in one of the tie-breaking helpers above.
Inputs that aren't ordinary numbers
All four functions convert their argument with the same rules as Number(). Special values pass through unchanged:
console.log(Math.round("2.5")); // 3
console.log(Math.floor(null)); // 0
console.log(Math.ceil(undefined)); // NaN
console.log(Math.trunc("12px")); // NaN
console.log(Math.floor(Infinity)); // Infinity
console.log(Math.round(NaN)); // NaN
console.log(Math.round(2 ** 60) === 2 ** 60); // trueThe last line shows that any double with magnitude at or above 2^52 is already an integer, so rounding it does nothing. If a large value looks wrong after rounding, the precision was lost before the rounding happened.
You may also see x | 0 or ~~x used as a fast trunc. These only work inside the 32-bit range and silently corrupt larger values. A later chapter on bitwise operators explains why. Prefer Math.trunc.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Using `trunc` for bins or grid cells | Bin 0 is twice as wide | Use `Math.floor` |
| Assuming `Math.round(-2.5)` is `-3` | Off-by-one on negative ties | Use a half-away-from-zero helper |
| `Math.round(x * 100) / 100` | `1.005` rounds to `1` | Shift through exponent strings |
| `ceil` on float arithmetic results | One extra page or batch | Work in integers or round first |
| Displaying `-0` | `"-0"` in localized output | Add `0` to normalize |
Exercise
A game grid uses cells 32 pixels wide. A sprite at x = -10 should be in cell -1. A colleague wrote Math.trunc(x / 32). What does it return for x = -10 and x = 10, and which function should be used?
Show answer
Math.trunc(-10 / 32) returns -0 and Math.trunc(10 / 32) returns 0. Both sprites end up in the same cell, so cell 0 covers 64 pixels. Math.floor(x / 32) returns -1 for x = -10 and 0 for x = 10, which is correct.
Exercise
Predict the output of Math.round(-1.5), Math.round(1.5), roundHalfEven(-1.5), and roundHalfAwayFromZero(-1.5) using the helpers from this chapter.
Show answer
Math.round(-1.5) is -1, because ties go toward positive infinity. Math.round(1.5) is 2. roundHalfEven(-1.5) is -2: Math.round gives -1, which is odd, so the helper subtracts 1. roundHalfAwayFromZero(-1.5) is -2.
Exercise
Why does Math.round(1.005 * 100) / 100 return 1, while roundTo(1.005, 2) returns 1.01?
Show answer
The literal 1.005 is stored slightly below 1.005, and multiplying by 100 gives 100.49999999999999, which rounds down to 100. roundTo builds the string "1.005e2", which parses directly to exactly 100.5, so Math.round gives 101. Shifting back with "101e-2" gives 1.01.