Two ways: how to format numbers to locale with currency

Two ways: how to format numbers to locale with currency

2023-03-08
2 min read

Overview

Displaying specific currency is important to deliver correct information. However, it's impossible to add all currency symbols and number format. This article is going to talk about how to add currency symbol and number format only with JavaScript functions.

First way: toLocaleString

toLocaleString() method in Number object enables language-sensitive number formatting. toLocaleString() takes locale code and option objects as parameters. toLocaleString() returns a string type of number. Option objects contains style and currency. Style must be "currency" for this time. Currency key should be matched witch declared locale in order to see correct output.

Example code

js
const number = 55000;

number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }); // "55.000,00 €"
number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }); // "¥55,000"
number.toLocaleString('en-CA', { style: "currency", currency: "CAD" }); // "$55,000.00"

Adding some options such as style and currency generates number format including currency unit. If locale and currency code are not matched, you are able to see example together with following code.

js
number.toLocaleString('ja-JP', { style: "currency", currency: "CAD" }); // CA$255,000.00

Second way: Intl.NumberFormat

Before using NumberFormat, you have to know what is Intl.

What is Intl ?

Intl object is namespace for the ECMAScript Internationalization API which provides language sensitive string comparison, number formatting, and date and time formatting. At this moment, we will use it for formatting currency.

Intl.NumberFormat()

The Intl.NumberFormat is used to make formatted number by Locale. It returns string including Intl.NumberFormat can make number including currency unit and formatted number.

Example code

js
const number = 55000;

new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number); 
// "55.000,00 €"
new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number); 
// "¥55,000"
new Intl.NumberFormat("en-CA", { style: "currency", currency: "CAD" }).format(number); 
// "$55,000.00"

The way is very similar as toLocaleString. It also displays number format along with currency symbol.

If you are looking for locale codes click the link.
If you want to see currency code click the link.

Ref

Free open source project made by Youngjin