skip to main content
Avatar of Nicklas Jarnesjö
Nicklas Jarnesjö

Format currency and units with locale in js with a breeze

code

Working with numbers, currency and other units can be a real pain itself. Then add locale to it the headache gets real.

There for when I found Int.Numberformat() I totally fell in love ❤️

Currency

Say for example you have have a number, price, you want to present in locale specific way you have to know specific formatting where to put space ,,, . or the currency symbol and so on.

Lets take a look at a price in EURO and we want to present if to our Swedish audience first

console.log(new Intl.NumberFormat('sv-SE', {style: 'currency', currency: 'EUR'}).format(123456.789))
// 123 456,79 €

Then want to present it to our friends in USA

console.log(new Intl.NumberFormat('en-US', {style: 'currency', currency: 'EUR'}).format(123456.789))
// €123,456.79

Amazing isn't it! It's just works.

Units

It's alls work with units too. For example liter, kilometer-per-hours and combine it with unitDisplay: 'long' and you will get in correct singular and plural.

console.log(
  new Intl.NumberFormat('sv-SE', {
    style: 'unit',
    unit: 'kilometer-per-hour',
    unitDisplay: 'long'
  }).format(50)
)
// 50 kilometer per timme

Caveat

Safari don't have fully support for other units then currency, decimal and percent both desktop and iOS right now.

Is Safari starting to be the new IE?

Discuss this post on Twitter