JavaScript Format Number as Currency – How to Format Currencies in JavaScript
Written by Kolade Chris | Sep 28, 2024 | #JavaScript | 5 minutes Read
While working on an eCommerce website using JavaScript, financial reports, or dealing with product data from an API, you’ll need to format certain numbers or strings as currencies or convert them to currencies.
You’ve come to the right place if you’re looking into how to format numbers as currency strings in JavaScript.
In this article, I’ll show you the manual approach first, then proceed to show you how to do it with the JavaScript Internationalization API (Intl Constructor)
.
The Manual Approach: A Generic Function that Takes a Number or String and Converts it to Currency
You could create a function that takes a number or string and converts it to your target currency:
This approach is not sustainable because it handles one currency.
What if you want to handle many other currencies? Well, you can modify the function to accept a currency symbol:
This approach is still not sustainable because it requires custom logic for different locales and currencies, making it complex and error-prone.
There’s a solution, though. That solution is the Intl.NumberFormat
object of the JavaScript Internationalization API.
Pardon the interruption…
Join my Free Newsletter
Subscribe to my newsletter for coding tips, videos from reputable sources, articles from OG tech authors, and a ton of other goodies.
No BS. No fluff. Just pure software development goodies on a Sunday every week.
Now unto how to format currencies with the Intl.NumberFormat
object…
How to Format Numbers as Currency with the Intl.NumberFormat()
Constructor
Using the Intl.NumberFormat()
constructor to format numbers as currency is an improvement over manual methods. It streamlines the process by automatically applying locale-specific rules. It also offers built-in support for various currencies.
You can create an instance of the Intl.NumberFormat
with the new keyword or without it:
You can also assign it to a variable:
The Intl.NumberFormat()
constructor takes two parameters – locale
and options
. It uses the .format()
method to do the actual number formatting.
Both parameters are optional, so you can use the Intl.NumberFormat()
constructor directly. This way, it’ll only add commas to the numbers to indicate it in either thousand, million, or more:
If you decide to use only the locale parameter, the number will be formatted as done in that location. Here’s what that looks like for Nigeria, Italy, and UK:
If you finally use the options
parameter with style
set to 'currency'
and currency
set to the currency in that locale, the number will be formatted as currency:
Finally, you can create a reusable function to format numbers as currency by taking advantage of the Intl.NumberFormat()
constructor:
Thank you for reading!