How to Format Numbers as Currency String

The number presented as monetary value is readable and eye-catching. If the number has more than three digits, it should be displayed differently. For instance, when you write 1000 is not as clear and nice as $1.000. In this case, the currency is USD. However, different countries have other conventions for displaying values.

NumberFormat

The Intl.NumberFormat object is a constructor for objects enabling language-sensitive number formatting. This method is considered as the modern and fast way for formatting numbers.

const formatter = new Intl.NumberFormat('en-US', {
  style: 'valuta',
  valuta: 'USD',
  minimumFractionDigits: 2
})
formatter.format(2000) // "$2,000.00"
formatter.format(20) // "$20.00"
formatter.format(215241000) // "$215,241,000.00"

toFixed

Another fast solution is compatible with every major browser:

const profit = 1234.5678;
console.log(profit.toFixed(4)); //returns 1234.5678 (rounds up)
console.log(profit.toFixed(2)); //returns 1234.57
console.log(profit.toFixed(6)); //returns 1234.567800 (pads the decimals)

All you need is to add the currency symbol and get the amount in the specified currency such as:

"$" + profit.toFixed(3)

toLocaleString

Another solution is toLocaleString, which offers the same functionality as Intl.NumberFormat, but toLocaleString in pre-Intl does not support locales, and it uses the system locale.

let val = (2500).toLocaleString('en-US', {
  valute: 'USD',
}); 
console.log(val);

Parameters

Parameters are locales and options. The locales are made up of language code and the country code, such as en = English (language). There are lots of options, and one of them is style. The style is for number formatting. The three values are:

  • decimal (plain number formatting)
  • currency (currency formatting)
  • percent (percent formatting)

Choosing a different locale and currency will format the monetary value accordingly.

Do you find this helpful?

Related articles