Menu

How to Convert Numbers to Currency in Javascript

Taufik Nurhidayat
1 min read
#programming #tutorial

In this post, we will learn how to convert numbers to currency, whether it's Rupiah, Dollar, Euro, or other currencies with Javascript. With Intl...

social_cards/currency_vz2qr6.png

In this post, we will learn how to convert numbers to currency, whether it’s Rupiah, Dollar, Euro, or other currencies with Javascript.

With Intl.NumberFormat

This method is recommended by MDN because of its faster performance. You need to create a new object of type Intl.NumberFormat.

const number = 3500;

console.log(new Intl.NumberFormat().format(number));
// → '3,500' if in English

or by adding Intl.NumberFormat to a variable/constant and adding the language and currency options.

const currency = new Intl.NumberFormat('id-ID', {
  style: 'currency',
  currency: 'IDR',
})
console.log(currency.format(3500))
// Output: "Rp 3.500,00"

Into Japanese with Japanese Yen currency.

const currency = new Intl.NumberFormat('ja-JP', {
  style: 'currency',
  currency: 'JPY',
})
console.log(currency.format(3500))
// Output: "¥3,500"

Into German with Euro currency.

const currency = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',
})
console.log(currency.format(3500))
// Output: "3.500,00 €"

With toLocaleString

You can also use toLocaleString() to convert numbers to currency.

const number = 123456.789
console.log(number.toLocaleString())
//Output locale 'en-US': "123,456.789"

Syntax

toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)

Display in language and add currency options. Same as Intl.NumberFormat.

const number = 3500
console.log(number.toLocaleString('id-ID', {
  style: 'currency',
  currency: 'IDR'
}))
//Expected output: "Rp 3.500,00"

Final Words

Basically, both methods are the same, but it is recommended to use Intl.NumberFormat for faster performance.