Rounding and Formatting Numbers
JavaScript has two families of tools for tidying a number. The Math methods round a number and return a number, which you can keep calculating with. The number methods toFixed(), toPrecision() and toExponential(), and the Intl.NumberFormat API, return a string for display. Keeping the two apart avoids a common bug where a formatted string ends up in a sum.
Rounding to a whole number
Section titled “Rounding to a whole number”| Method | What it does |
|---|---|
Math.round(x) |
rounds to the nearest whole number, with halves going up |
Math.floor(x) |
rounds down, towards minus infinity |
Math.ceil(x) |
rounds up, towards plus infinity |
Math.trunc(x) |
drops the fraction, which rounds towards zero |
The four differ most on halves and on negative numbers:
const weights = [2.4, 2.5, 2.6, -2.5, -2.6];
for (const w of weights) { console.log(w, Math.round(w), Math.floor(w), Math.ceil(w), Math.trunc(w));}This prints:
2.4 2 2 3 22.5 3 2 3 22.6 3 2 3 2-2.5 -2 -3 -2 -2-2.6 -3 -3 -2 -2Math.round(-2.5) gives -2, not -3, because “halves go up” means towards plus infinity, not away from zero. Math.floor and Math.trunc agree on positive numbers and differ on negative ones.
Formatting a number as text
Section titled “Formatting a number as text”toFixed(digits) gives a fixed number of decimal places, toPrecision(digits) gives a number of significant figures, and toExponential(digits) gives scientific notation with that many digits after the point. All three round, and all three return strings:
const distance = 1534.4862;
console.log(distance.toFixed(2));console.log(distance.toFixed(0));console.log(distance.toPrecision(3));console.log(distance.toPrecision(6));console.log(distance.toExponential(2));console.log((0.000427).toPrecision(2));This prints:
1534.4915341.53e+31534.491.53e+30.00043toPrecision(3) switches to exponential form when the whole part has more digits than the precision asked for. With a small number such as 0.000427, significant figures start at the first non-zero digit, so the leading zeros do not count.
The brackets in (0.000427).toPrecision(2) matter only when calling a method directly on a number literal, because the parser would otherwise read the first . as a decimal point. A variable needs no brackets.
Because the result is a string, adding to it joins text rather than adding numbers:
const basket = [4.99, 12.5, 0.75];const total = basket.reduce((sum, price) => sum + price, 0);const label = total.toFixed(2);
console.log(label + 1);console.log(Number(label) + 1);This prints:
18.24119.24Format at the last moment, when the value is about to be shown, and keep the number for any further arithmetic.
Floating-point surprises
Section titled “Floating-point surprises”Numbers in JavaScript are stored in binary, and most decimal fractions have no exact binary form. The stored value is the closest one available, which is sometimes slightly below the decimal you wrote:
console.log((1.005).toFixed(2));console.log((1.005).toPrecision(20));console.log(Math.round(1.005 * 100) / 100);console.log(0.1 + 0.2);This prints:
1.001.004999999999999893410.300000000000000041.005 is really stored as a little under 1.005, so toFixed(2) correctly rounds it down. For money, the usual fix is to work in whole pennies and divide by 100 only for display. Intl.NumberFormat, below, rounds from the shortest decimal form of the number, so it gives the answer most people expect.
Formatting for a locale
Section titled “Formatting for a locale”Intl.NumberFormat formats a number for a particular language and region, adding thousands separators, a currency symbol or a percent sign. Pass the locale explicitly, such as 'en-GB', because otherwise it uses the locale of the browser or the system, and the output changes from one user to the next:
const total = 1234567.891;
console.log(new Intl.NumberFormat('en-GB').format(total));
const pounds = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP' });console.log(pounds.format(total));
const euros = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' });console.log(euros.format(total));
const percent = new Intl.NumberFormat('en-GB', { style: 'percent', maximumFractionDigits: 1 });console.log(percent.format(0.1234));
const compact = new Intl.NumberFormat('en-GB', { notation: 'compact' });console.log(compact.format(total));
console.log(total.toLocaleString('en-GB', { maximumFractionDigits: 1 }));This prints:
1,234,567.891£1,234,567.891.234.567,89 €12.3%1.2m1,234,567.9The currency style rounds to the currency’s usual number of decimal places, and the German locale swaps the roles of the comma and the full stop. toLocaleString() takes the same locale and options, and is convenient for a one-off. Create the formatter once and reuse it when formatting many numbers, because building one does the expensive locale lookup.
maximumFractionDigits caps the decimal places without padding, while minimumFractionDigits pads with zeros, so the two together fix the number of places just as toFixed() does:
const twoPlaces = new Intl.NumberFormat('en-GB', { maximumFractionDigits: 2 });console.log(twoPlaces.format(1.005));console.log(twoPlaces.format(2.5));console.log(twoPlaces.format(4));This prints:
1.012.54Reading numbers back out of text is covered in ParseInt and ParseFloat.
Steve Griffith covers this topic in his video Rounding and Formatting Numbers.