DEV Community

Cover image for Format numbers easily and nicely
Dzmitry Hutaryan
Dzmitry Hutaryan

Posted on

Format numbers easily and nicely

Intro

We all use such data as numbers. Sometimes it's necessary to format numbers depending on language. Especially it's related to currencies. What if I'll tell you can use native javascript feature for that? Welcome Intl.NumberFormat- ES6 feature. Let me show you a few examples.

Basic

It's easy to use. All you need is your locale name:

new Intl.NumberFormat('en').format(5000.13) // 5,000.13
new Intl.NumberFormat('ru').format(5000.13) // 5 000,13
Enter fullscreen mode Exit fullscreen mode

More over, we can use short form and it will be automatically rounded. Let's add some additional options for that:

new Intl.NumberFormat('en', {
  notation: 'compact',
}).format(5000.13) // 5K

new Intl.NumberFormat('hi', {
  notation: 'compact',
}).format(5000.13) // 5 हज़ार

new Intl.NumberFormat('ru', {
  notation: 'compact',
}).format(5000.13) // 5 тыс.

new Intl.NumberFormat('en', {
  notation: 'compact',
}).format(10500.13) // 11K
Enter fullscreen mode Exit fullscreen mode

Currency

Intl allows to add a currency sign as well. No need to handle it by ourselves:

new Intl.NumberFormat('en', {
  style: 'currency',
  currency: 'USD',
}).format(5000) // $5,000.00

new Intl.NumberFormat('he', {
  style: 'currency',
  currency: 'ILS',
}).format(5000) // 5,000.00₪
Enter fullscreen mode Exit fullscreen mode

By the way, currency sign position depends on locale:

new Intl.NumberFormat('ru', {
  style: 'currency',
  currency: 'USD',
}).format(5000) // 5 000,00 $
Enter fullscreen mode Exit fullscreen mode

Range

From time to time we need to show a range of numbers. Intl has formatRange method for that:

const intl = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 1,
});

console.log(intl.formatRange(3, 5)); // $3.0 – $5.0
console.log(intl.formatRange(2.9, 3.1)); // $2.9 – $3.1
Enter fullscreen mode Exit fullscreen mode

formatRange has interesting behaviour. It will add the "approximately equals" symbol if startRange and endRange round to the same values.

const intl = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 0, // no numbers after dot, only integer
});

console.log(intl.formatRange(1.9, 3.1)); // $2 – $3
console.log(intl.formatRange(2.9, 3.1)); // ~$3
Enter fullscreen mode Exit fullscreen mode

Now, you know a bit more.

Top comments (0)