Sub topic 9
Displaying Numbers: toFixed, toPrecision, toString(radix), and Intl.NumberFormat
This chapter assumes you know how JavaScript stores numbers as IEEE 754 doubles, why values like 1.005 are not stored exactly, and how numeric literals such as 0xff and 1_000_000 are written. Those topics are covered in earlier chapters. This chapter covers what happens when you turn a number into a string to show someone.
A stored number and its displayed form are separate things. A stored number is a binary value. A displayed form is a string you choose: fixed decimals, a set number of significant digits, a different base, or a locale-aware format with currency symbols and grouping separators. Every method here returns a string. That is intentional, and it is the most common source of bugs.
The Default: String(n) and Implicit Conversion
Without any formatting, JavaScript prints the shortest decimal string that converts back to the same double. Very large and very small values switch to exponent notation.
console.log(String(0.1)); // "0.1"
console.log(String(0.1 + 0.2)); // "0.30000000000000004"
console.log(String(123e19)); // "1.23e+21"
console.log(String(1e20)); // "100000000000000000000"
console.log(String(0.000001)); // "0.000001"
console.log(String(0.0000001)); // "1e-7"
console.log(String(-0)); // "0"The default switches to exponent form at 1e21 and above, and below 1e-6. It also hides the sign of negative zero. If a user can ever see a number, choose its format yourself.
toFixed: A Set Number of Decimal Places
toFixed(digits) rounds to digits places after the decimal point and pads with zeros. digits must be from 0 to 100. Any other value throws a RangeError.
console.log((3.14159).toFixed(2)); // "3.14"
console.log((2).toFixed(2)); // "2.00"
console.log((2.5).toFixed(0)); // "3"
console.log((-2.5).toFixed(0)); // "-3"
console.log(Math.round(-2.5)); // -2
console.log((1.005).toFixed(2)); // "1.00"
console.log((1e21).toFixed(2)); // "1e+21"
console.log((-0).toFixed(2)); // "0.00"
try {
(1).toFixed(101);
} catch (e) {
console.log(e instanceof RangeError); // true
}Gotcha: toFixed rounds the stored binary value
toFixed rounds the exact binary value, not the decimal you typed. 1.005 is stored as about 1.00499999999999989, so it rounds down to "1.00". The method is working correctly on a value you did not intend to store.
Gotcha: halves round away from zero
On an exact tie, toFixed rounds the magnitude up, so -2.5 becomes "-3". Math.round rounds ties toward positive infinity and gives -2. Use one rule consistently in a single report, or totals will not match.
Gotcha: the result is a string
const price = (19.999).toFixed(2); // "20.00"
console.log(price + 1); // "20.001" (string concatenation)
console.log(Number(price) + 1); // 21Do your calculations on numbers, and call toFixed only at the display step. Do not round-trip through toFixed to round values partway through a calculation. For money, store integer cents and divide only when formatting.
toPrecision and toExponential: Significant Digits
toPrecision(p) keeps p significant digits, where p is from 1 to 100. It picks fixed or exponent notation for you. It uses exponent form when the exponent is below -6, or when the exponent is at least p, which means the integer part has more digits than p allows.
console.log((123.456).toPrecision(4)); // "123.5"
console.log((123456).toPrecision(2)); // "1.2e+5"
console.log((0.000123).toPrecision(2)); // "0.00012"
console.log((0.0000001234).toPrecision(2)); // "1.2e-7"
console.log((5).toPrecision(3)); // "5.00"
console.log((12345).toExponential(2)); // "1.23e+4"
console.log((0.00042).toExponential()); // "4.2e-4"Use toPrecision for measurements, where significant digits matter more than decimal places. Use toExponential when you always want scientific notation. Because toPrecision switches notation on its own, it is a poor fit for table columns that need to line up.
toString(radix): Other Bases
toString(radix) writes the number in a base from 2 to 36. Digits above 9 use the lowercase letters a to z.
console.log((255).toString(16)); // "ff"
console.log((255).toString(2)); // "11111111"
console.log((-255).toString(2)); // "-11111111"
console.log((0.5).toString(2)); // "0.1"
console.log((5).toString(2).padStart(8, "0")); // "00000101"
console.log(255..toString(16)); // "ff"
console.log((255).toString(16).toUpperCase()); // "FF"Keep these points in mind:
255.toString(16)is a syntax error, because the parser reads255.as a number literal. Write(255),255..toString(), or call the method on a variable.- Negative numbers come out as a minus sign plus the magnitude. You do not get two's complement. For a 32-bit two's-complement view, use
(n >>> 0).toString(2). - Leading zeros are not added. Use
padStartto get them. - Fractions also convert.
(0.1).toString(2)produces a long binary string, which shows that 0.1 has no exact binary form. - To go back the other way, use
parseInt(str, radix).
Intl.NumberFormat: Locale-Aware Display
Intl.NumberFormat handles what the methods above cannot: grouping separators, the local decimal mark, currency symbols, percentages, units, and compact notation.
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const eur = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
const pct = new Intl.NumberFormat("en-US", { style: "percent", maximumFractionDigits: 1 });
const compact = new Intl.NumberFormat("en-US", { notation: "compact" });
const speed = new Intl.NumberFormat("en-US", { style: "unit", unit: "kilometer-per-hour" });
const fixed2 = new Intl.NumberFormat("en-US", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
console.log(usd.format(1234.5)); // "$1,234.50"
console.log(eur.format(1234.5)); // "1.234,50 €"
console.log(pct.format(0.256)); // "25.6%"
console.log(compact.format(1234567)); // "1.2M"
console.log(speed.format(50)); // "50 km/h"
console.log(fixed2.format(1234567.891)); // "1,234,567.89"
console.log(fixed2.format(-0)); // "-0.00"
console.log((1234.5).toLocaleString("en-US")); // "1,234.5"Options worth knowing
| Option | Purpose | Example values |
|---|---|---|
| `style` | Kind of output | `"decimal"`, `"currency"`, `"percent"`, `"unit"` |
| `currency` | Required when `style` is `"currency"` | `"USD"`, `"EUR"`, `"JPY"` |
| `minimumFractionDigits` / `maximumFractionDigits` | Decimal places | `0` to `100` |
| `maximumSignificantDigits` | Significant digits, overrides the fraction-digit options | `1` to `21` |
| `notation` | Number layout | `"standard"`, `"scientific"`, `"engineering"`, `"compact"` |
| `useGrouping` | Show thousands separators | `true`, `false` |
| `signDisplay` | When a sign appears | `"auto"`, `"always"`, `"exceptZero"`, `"never"` |
Gotchas with Intl
- Percent multiplies by 100. Pass
0.256, not25.6. - Currency sets its own decimal places.
JPYformats with 0 decimals andUSDwith 2, unless you override them. - The output contains special spaces. Many locales put a non-breaking space (U+00A0) or a narrow no-break space (U+202F) between the number and the symbol. A test that compares against
"1.234,50 €"typed with a normal space will fail. UseformatToPartsor normalize the spaces before comparing. - Negative zero shows its sign.
signDisplay: "auto"prints"-0.00"for-0, whichtoFixeddoes not. Add+ 0to the value (-0 + 0is0), or usesignDisplay: "exceptZero"when that matters. - Output is not stable across engines. Locale data can change between browser and Node.js versions. Never parse formatted strings back into numbers, and never store them as data.
- Reuse formatters. Building a formatter is far more expensive than calling
format. Create it once outside loops.toLocaleStringbuilds a new one on every call.
formatToParts returns the pieces with type labels, which helps with custom styling:
const parts = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })
.formatToParts(-1234.5);
console.log(parts.map(p => `${p.type}:${p.value}`).join(" | "));
// "minusSign:- | currency:$ | integer:1 | group:, | integer:234 | decimal:. | fraction:50"Choosing a Method
Exercises
Exercise
What do (0.5).toFixed(0), (1.5).toFixed(0), and (-1.5).toFixed(0) return, and how does Math.round(-1.5) differ?
Show answer
They return "1", "2", and "-2". All three are exact halves, and toFixed rounds the magnitude away from zero. Math.round(-1.5) returns the number -1, because it rounds ties toward positive infinity. Math.round also returns a number, while toFixed returns a string.
Exercise
Write a function toHexByte(n) that formats an integer from 0 to 255 as two uppercase hex digits, so that 10 becomes "0A" and 255 becomes "FF".
Show answer
function toHexByte(n) { return n.toString(16).toUpperCase().padStart(2, "0"); } Calling toString(16) gives "a" for 10, toUpperCase makes it "A", and padStart adds the leading zero.
Exercise
A cart total is stored as the integer 123456 (cents). Show how to display it as "$1,234.56" and explain why you should not compute (total / 100).toFixed(2) and then add "$" and commas yourself.
Show answer
Use new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(123456 / 100). The formatter adds grouping, the symbol, and the correct currency decimals, and it adapts to other locales and currencies. Building the string by hand hard-codes the comma and dot conventions, ignores currencies like JPY that have no minor unit, and is easy to get wrong for negative amounts.
Exercise
Why does (123456).toPrecision(2) return "1.2e+5" while (123456).toFixed(0) returns "123456"?
Show answer
toPrecision keeps only 2 significant digits. The exponent of 123456 is 5, which is at least the precision of 2, so the value cannot be written in fixed form without extra digits, and the method switches to exponent notation. toFixed controls only decimal places and always writes the full integer part for values below 1e21.