Formatting Euros and Percentages With Intl.NumberFormat
In this lesson, you formatted the batch planner’s green beans and cost lines for the café chain’s 1200 kg order, with thousands separators, euros and percentages, so they print what the Python script prints.
- In Python, the spec after the colon does the formatting: in
,.2f, the comma asks for thousands separators and.2ffor two decimals. JavaScript’s template literals have no format specs, and.toFixed(2)covers only the decimals. - JavaScript has a built-in formatter instead,
Intl.NumberFormat(Intl is short for internationalization). You build one formatter for each way you print a number, withnew, which creates a formatter object and gets a proper treatment later. - The first argument names the locale, the language and region whose number conventions to follow.
"en-US", US English, uses commas and points, as Python’s,spec does. The second is an object literal of options:style: "currency"withcurrency: "EUR"formats euros, and adds the euro sign. - Watch out: Python’s
,spec ignores the locale, but a formatter follows one, so always name it. Leave it out, and JavaScript uses the machine’s: on a server set to German the same total prints as10.459,06 €. - Call
.format()on the output line. Like.toFixed(), it returns a string, so the value stays a number until then. style: "percent"multiplies by 100, rounds to a whole percent and adds the sign, as Python’s.0%does, with the same caveat on exact halves as.toFixed(). The last part batch’s share of a drum,0.6470588235294107, prints as65%.- For
,.1f, setminimumFractionDigitsandmaximumFractionDigitstogether, both to 1. The minimum pads with zeros (1,200.0); the maximum rounds off the digits past the last one you keep (1,411.8). - The green beans line is long, so it’s split in two. Python joins f-strings that sit side by side,
but JavaScript doesn’t join literals, so a
+joins the two template literals. - For one value printed once, every number has
.toLocaleString(), which takes the same locale and options:greenKg.toLocaleString("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 })is1,411.8, with no formatter to keep. - Keep values as numbers through every calculation and format them last.
.toFixed()is enough for plain decimals; for anything a person reads, useIntl.NumberFormatwith the locale named.
Here are the planner’s two output lines in Python:
print(f"Green beans: {green_kg:,.1f} kg "
f"(roast loss {WEIGHT_LOSS:.0%})")
print(f"Green coffee: €{total:,.2f} with delivery")