Formatting currency with JavaScript Intl
Dec 17, 2020
JavaScript's Internationalization API allows you to format currency. It takes the locale and options to configure the currency we're using. The options require the style to be set to currency
and a currency option to specify the unit type, as this is returned as part of the result.
1Intl.NumberFormat("LOCALE", {
2 style: "currency",
3 currency: "CURRENCY UNIT"
4}).format(VALUE); // => "€1.23"
The following example formats a EUR
(Euro) currency of the value 1.2345
into a en-GB
(English - Great Britain) format.
1Intl.NumberFormat("en-GB", {
2 style: "currency",
3 currency: "EUR"
4}).format(1.2345); // => "€1.23"
To save configuring this each time we use the formatting it can be wrapped in a function and the values passes to it. This example tahe the value and optionally a locale, defaulting to en-GB
. It returns a USD
value formatted to the input locale.
1const formatUSDCurrency = (value, locale = "en-GB") => { return Intl.NumberFormat(locale, {
2 style: "currency",
3 currency: 'USD'
4}).format(value); };
1formatUSDCurrency(1230000) // => "US$1,230,000.00"
2formatUSDCurrency(1230000, "de-DE") // => "1.230.000,00 $"
3formatUSDCurrency(1230000, "fr-FR") // => "1 230 000,00 $US"
You can also configure significant digits, plus/minus signs and other settings as needed.
You can either specify the locale yourself, as I have done above, or you can get the user locale from the browser.