Rounding
suggest changeNearest integer
Math.round() rounds to the nearest integer. Exact half values are rounded toward positive infinity:
Math.round(2.3); // 2
Math.round(2.5); // 3
Math.round(-2.5); // -2
Math.round(-2.7); // -3
Up, down, and toward zero
Math.ceil(2.3); // 3: toward positive infinity
Math.ceil(-1.1); // -1
Math.floor(2.7); // 2: toward negative infinity
Math.floor(-1.1); // -2
Math.trunc(2.7); // 2: remove the fractional part
Math.trunc(-2.7); // -2
Avoid bitwise tricks such as value | 0 for truncation. Bitwise operators convert values to 32-bit integers and can silently wrap larger numbers.
Decimal places
Scale, round, and scale back when ordinary binary floating-point precision is suitable:
function roundTo(value, places = 0) {
const factor = 10 ** places;
return Math.round((value + Number.EPSILON) * factor) / factor;
}
roundTo(2 / 3, 2); // 0.67
roundTo(10000 / 3, -2); // 3300
The Number.EPSILON adjustment helps with some representation boundaries but is not a general decimal-arithmetic solution. Financial and other exact decimal calculations should use an appropriate decimal or integer-based representation.
For display rather than calculation, prefer Intl.NumberFormat:
const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
formatter.format(2 / 3); // '0.67'
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents