round, floor, ceil and trunc on your own numbers: where does each take a negative number, or one at exactly .5? Also prices to cents and banker’s rounding. An…
Why it matters
Rounding is in prices, pages, progress bars, coordinates. Using floor where you meant trunc is a silent off-by-one for negative numbers, Math.round(-2.5) giving -2 is a frequent calculation bug, and Math.round(1.005 * 100) / 100 gives 1.
The key idea
round, floor, ceil have a fixed direction; trunc goes toward zero
Common mistakes
Using Math.floor to "cut to a whole number" Wrong for negative numbers: floor(-7.9) is -8. Use Math.trunc, which gives -7 (the decimals dropped).
Thinking Math.round takes .5 away from zero Math.round takes an exact half up, toward plus infinity: round(-2.5) is -2, not -3. To go away from zero: Math.sign(n) * Math.round(Math.abs(n)).
Looking for banker’s rounding (half to even) Math has none. Intl.NumberFormat has roundingMode: 'halfEven' in new browsers (check resolvedOptions().roundingMode); in old ones, work it out yourself.
Try it in this playground
Part floor and trunc -2.4: floor -3, trunc -2. For positive numbers they agree.
Math.round(-2.5) -2, not -3: an exact half is taken up.
An x.xx5 price to two decimals 1.005 becomes 1: n * 100 gives 100.49999999999999.
Banker’s roundingroundingMode: 'halfEven' on an exact half: to the even digit.