Displaying currency formatted depending on user language/region is not uncommon task in web development.
It can be easily achieved with usage of Intl
, which is a namespace in browser API and part of ECMAScript Internationalization API.
The Intl namespace object contains several constructors as well as functionality common to the internationalization constructors and other language sensitive functions. Collectively, they comprise the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, date and time formatting, and more. MDN Intl page
Code
This is ready to use code that display amount
of currency
formatted for given locale
. These data are usually taken from API or application state or in case of locale from browser API.
function formatCurrency(locale,amount,currency){
const formatter = new Intl.NumberFormat(locale,
{
style:'currency',
currency: currency
});
return formatter.format(amount);
}
And this is all that you need. Simple function that can be used in any framework, no npm packages needed, no dictionaries with currency symbols etc.
There other options that can be set to customize how currency is presented, all of them well described on MDN as well. Interactive examples are there as well so I will not rewrite them here.
Let the browser worry
Even if your application is not localized or uses only single currency it is convenient to let the browser worry about how currency should be displayed:
- what is currency symbol ?
- should symbol be placed before or after amount?
- use spaces or comma for separating thousands and decimal separator.
Other thing is that using standardized formatting assures that screen readers and other assistive technologies will read that data correctly.
Top comments (0)