Basics
Rounding: Math.round, floor, ceil, toFixed
Three ways to round to a whole number and one to round to a number of places for display.
Why it exists
A computer stores fractions in binary, and many decimal fractions are inexact there: 0.1 + 0.2 gives 0.30000000000000004. You can't show that to a user, and comparing it is risky. Besides, tasks themselves need different rounding: the number of pages always rounds up, whole years of age always round down, a rating rounds to tenths.
Where it's used
- The number of pages:
Math.ceil(total / perPage)— a partial page is still a page. - Whole units:
Math.floor(seconds / 60)— how many full minutes passed. - Showing prices and ratings:
rating.toFixed(1)→"4.5". - Random whole numbers:
Math.floor(Math.random() * 6).
Syntax
Math.round(x)
Math.floor(x)
Math.ceil(x)
number.toFixed(digits)Examples
Math.round(4.5); // → 5
Math.floor(4.9); // → 4
Math.ceil(4.1); // → 50.1 + 0.2; // → 0.30000000000000004
Math.round((0.1 + 0.2) * 100) / 100; // → 0.3const total = 41;
const perPage = 10;
Math.ceil(total / perPage); // → 5(4.456).toFixed(2); // → "4.46"
(2).toFixed(2); // → "2.00"toFixed returns a string with the given number of placesResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Math.round(x)— to the nearest whole number; exactly.5rounds up (towards +∞):Math.round(2.5)is3, andMath.round(-2.5)is-2.Math.floor(x)— down, to the smaller whole number:Math.floor(-1.5)is-2.Math.ceil(x)— up, to the larger whole number.Math.trunc(x)— simply drops the fractional part.
All of them round to a whole number. To round to tenths, shift the decimal point: Math.round(x * 10) / 10.
x.toFixed(n) rounds to n places after the point and returns a string with exactly n places: (2).toFixed(2) is "2.00". It's a display format, not something to compute with.
Traps
How it differs from…
- The
Mathobject All the rounding functions are part of the
Mathobject, which has other helpers too:max,min,abs.Number.isInteger()Number.isInteger checks whether a number is whole; the rounding functions make a number whole.
When to pick something else
Don't round intermediate results — only the final one: rounding errors accumulate. And don't use toFixed if you still need to compute with the result — it's for display. For formatting by a country's rules (spaces, commas, currency), there's Intl.NumberFormat.
Practice
Lessons where this appears
- Celsius to FahrenheitLab · Chapter 1 · Variables and types
- Byte becomes an accountantTale · Chapter 4 · Numbers and Math
- The till at Purr & PastryWorkshop · Chapter 4 · Numbers and Math
- The case of the $349.90150.00 receiptInvestigation · Chapter 4 · Numbers and Math
- The AuditorBoss · Chapter 4 · Numbers and Math