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.
Intl.NumberFormat("LOCALE", { style: "currency", currency: "CURRENCY UNIT"}).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.
Intl.NumberFormat("en-GB", { style: "currency", currency: "EUR"}).format(1.2345); // => "β¬1.23"
To save configureing 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.
const formatUSDCurrency = (value, locale = "en-GB") => {
return Intl.NumberFormat(locale, {
style: "currency",
currency: 'USD',
}).format(value);
};
formatUSDCurrency(1230000) // => "US$1,230,000.00"
formatUSDCurrency(1230000, "de-DE") // => "1.230.000,00 $"
formatUSDCurrency(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.
Top comments (0)