How to format numbers

The native Intl.NumberFormat API lets you format numbers for specific languages without any external dependencies.

The internationalization API in browsers has improved a lot in the last few years. This is the second blog post in a series that will show neat little examples to help us get more familiar with the native Intl APIs.

This post will bring up the basics of using the Intl.NumberFormat constructor to format numbers.

Using Intl.NumberFormat

const formatter = new Intl.NumberFormat();

console.log(formatter.format(1234));
// 1,234

The constructor Intl.NumberFormat will default to the language the browser runs in and will automatically format numbers for that language. If you rather want to select a language that the rest of your service uses, just pass that locale as the first argument the the Intl.NumberFormat constructor like so:

const formatter = new Intl.NumberFormat('sv-SE');

console.log(formatter.format(1234));
// 1 234

Rounding digits when formatting numbers

Sometimes it's also useful to control the number of decimals, for example when rendering tables, there are two options for this, maximumFractionDigits and minimumFractionDigits. If both are set to the same value you will get a fixed amount of decimal numbers.

const formatter = new Intl.NumberFormat('en-GB', {
  maximumFractionDigits: 2,
  minimumFractionDigits: 2
});

console.table([
  {height: 174.3, weight: 67},
  {height: 201.3378, weight: 92.7323},
  {height: 167.2341, weight: 57}
].map((person) => ({
  height: formatter.format(person.height),
  weight: formatter.format(person.weight)
})));

/*
(index)   height    weight
0         174.30    67.00
1         201.34    92.73
2         167.23    57.00
*/

More information

The Intl.NumberFormat API provides several more configuration options, you can read more about them at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat .

Happy coding!