Formatting Signs, Units, and Locales

With roundingMode: "halfEven" in its percent formatter, the port’s Bluebell line says 12%, as the Python script does. The bookkeeper’s report has more to print, though. Below the invoice lines, it shows how each café’s order changed since September. In November, a new café in Aachen wants its invoices in German.

A Python f-string handles each of these with a formatting detail, like a + flag in the spec, a unit typed after the number, or a decimal point that never changes. In JavaScript, you control each one with an Intl.NumberFormat, the formatter object you build once with a locale and a style and then call .format() on. Start with the sign.

Show the Change Since September With a Sign

The report compares each café’s October kilos with September’s and prints the change as a whole percent with its sign. Here’s the Python:

Language: Python
cafes = [
    {"name": "Larder Lane", "kg": 36.0, "september_kg": 40.5},
    {"name": "Bluebell Café", "kg": 9.0, "september_kg": 8.0},
    {"name": "Northside Kitchen", "kg": 27.0, "september_kg": 35.0},
]

for cafe in cafes:
    change = cafe["kg"] / cafe["september_kg"] - 1
    print(f"{cafe['name']}: {change:+.0%} since September")

It prints -11%, +12%, and -23%. The + in the spec puts a sign on positive numbers too. In the JavaScript port, that’s the signDisplay option set to "always":

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.