brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: JavaScript's Intl.NumberFormat formats euros and big numbers the local way

Javascript
~/tips/tip-javascript-intl-numberformat

new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(123456.789);

Formats prices and large numbers per language and currency, without your own string code.

Formatting a price by hand means deciding on dots, commas, the euro sign and where it goes. In the Netherlands and Germany that is different from the US. The browser already knows all of this.

new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(123456.789);
// "123.456,79 €"

That is MDN’s own example. Change the locale, for example to "nl-NL" for Dutch visitors, and you get that country’s conventions without changing anything else.

For dashboards there is the compact notation:

new Intl.NumberFormat("en-GB", { notation: "compact", compactDisplay: "short" }).format(987654321);
// "988M"

Short is the default for compact; compactDisplay: "long" writes the word out, like “988 millions” in French.

For a whole table, I’d make one formatter and call .format() on it for each value, which also keeps the settings in one place.

Caveats. The currency style needs a currency; without it the constructor throws a TypeError. The exact output can differ slightly between browsers and versions, so do not compare formatted strings in tests. And it formats; it does not convert. Showing currency: "EUR" on a number that is in dollars just puts the wrong sign on it. MDN marks the API widely available since September 2017.

Further reading: MDN: Intl.NumberFormat, MDN: Intl.NumberFormat() constructor

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link