I was working on an eCommerce website recently and had to format quite a few numbers. Some needed to be rounded to two decimals, others to be shown with a currency, and just as I was starting to be overwhelmed with all the styles – Intl.NumberFormat came to the rescue.
Intl.NumberFormat allows us to easily transform any number into a currency that will be displayed according to a specific country/currency style. For example:
let total = 12345.6752;
—> gives us ‘€12,345.68′
let formatCurrency = new Intl.NumberFormat(undefined, {style: 'currency', currency: 'EUR' });
const totalEUR = formatCurrency.format(total)
Let’s look at it step by step. We declared formatCurrency that creates a new Intl.NumberFormat constructor that takes two arguments: a locale (we pass in undefined as we want to use visitors’ default language) and an object of options. In there we define the style property which is currency, and once we did that we also had to define which currency we want – in this example euro. As a result, we get the rounded number (bye, bye annoying decimals) displayed with the chosen currency.
The options object that we passed as the second argument offers more handy options (like units) so I encourage reading more about it here.
P.S. Note two little details – there is no default currency. If style property is currency then you have to define it yourself. And second – you’ll be given back a string so just keep that in mind so you don’t get lost between type changes.