Currency formatting on JavaScript ES6
Ken Aqshal Bramasta / June 26, 2022
1 min read • ––– views
1const money = 10000;
2
3new Intl.NumberFormat('jp-JP', {
4 style: 'currency',
5 currency: 'JPY',
6}).format(money); // 'JP¥ 10,000'
7
8new Intl.NumberFormat('de-DE', {
9 style: 'currency',
10 currency: 'EUR',
11}).format(money); // '€ 10,000.00'
Guide for the parameter
Let's talk about the parameters. It's made up of the locales and the options object.
1new Intl.NumberFormat([locales[, options]])
Parameter: Locales
First, you have the locales
, this is the language and region settings. It is made up of language code and the country code.
1language code + country code
2
3//ex-1
4en-CA
5en = English (language)
6CA = Canada (country)
7
8//ex-2
9de-DE
10de = German (language)
11DE = Germany (country)
12
list of the Language code
list of the Country code
Parameter: Options
There are tons of options, but let's just talk about the two that we're using: styles
, and currency
.
Options: Style
The style is the easy part. This is the style for your number formatting. Since this is a currency blog, our choice would be currency
. The 3 possible values are:
- decimal (plain number formatting, the default)
- currency (currency formatting, what we're using)
- percent (percent formatting)
1const money = 100;
2
3new Intl.NumberFormat('en-CAD', { currency: 'CAD'
4 style: 'decimal',
5}).format(money); // '100'
6
7new Intl.NumberFormat('en-CAD', { currency: 'CAD'
8 style: 'currency',
9}).format(money); // 'CA$ 100.00'
10
11new Intl.NumberFormat('en-CAD', { currency: 'CAD'
12 style: 'percent',
13}).format(money); // '10,000%'
Options: Currency
Obviously, there are tons of currency options. You can see the full list here
Here are some examples:
- CAD (Canadian dollar)
- USD (US dollar)
- EUR (Euro)
- CNY (Chinese RMB)
Resources
- MDN Web Docs - Intl.NumberFormat
- w3schools: Language Codes
- w3schools: Country Codes
- Current currency & funds code list
Enjoyed this post?
Check out some of my other articles: