When we are displaying numbers on a web page, we have to make sure that they are easy to read, and the reader should understand what that number wants to convey. In this article, we will learn different methods to add commas and currency symbols to make our currency values more user-friendly on a webpage.
How to Format Currency in JavaScript?
Whether we are dealing with currency values, statistical figures, or any other numerical information, adding commas to separate thousands, millions, and beyond can be a really good option.
When we are displaying a number as currency on a webpage, we have to add the proper symbols at the start, i.e., $ (US Dollar), € (Euro), etc. Also, we have to format it by placing commas in the proper places.
JavaScript offers several methods for formatting currency. Here we will cover three different methods, i.e., leveraging the Intl.NumberFormat() object, utilizing the toLocaleString() method, and using regular expressions. Each approach has its advantages and use cases; let’s explore each of them in detail.
1) Intl.NumberFormat() Object
This is a built-in JavaScript object and provides language-sensitive number formatting. We first have to create a new instance of Intl.NumberFormat(), which basically takes two major parameters, locales and options. These parameters are optional; if we don’t pass any locale or option, it will only format the number by adding commas.
The locale parameter can be passed as a string and it helps us to structure numbers based on specific locales, taking into account the formatting conversions of that particular region. This method is very useful when we have to format numbers for different regions or languages, such as currency formatting.
The second argument is ‘options’, a JavaScript object that holds other parameters. This is the main parameter for currency formatting.
It is written as options(style, currency, …). Here, the ‘style’ parameter is used to specify the type of formatting. Note that we will use ‘currency’ for style. Next, the ‘currency’ parameter is used to specify the currency we want to format, i.e., ‘USD’, ‘CAD’, ‘INR’, and so on.
So this parameter will return our number with a proper currency symbol; we don’t have to concatenate it manually.
After that we have to call the format() method of the formatting object, passing the number we want to format. We can then store the result in a variable, as shown below:
// Define a numeric value const number = 1234567890; // Create an Intl.NumberFormat object with 'en-US' locale const formatter = new Intl.NumberFormat('en-US', { style: 'currency', // Specify the currency code for US Dollars currency: 'USD', }); // Use the formatter to format the number according to the 'en-US' locale const formattedNumber = formatter.format(number); // Display the formatted number console.log(formattedNumber);
Output:
$1,234,567,890.00
2) toLocaleString() Method
This is also a built-in method in JavaScript. By the use of this method, we can format numbers by following a specific country’s formatting rules. By default, it follows the formatting conventions of the United States ( en-US ). But we can specify different locales according to our needs.
In this method also, we have to pass other parameters like ‘style’ and ‘currency’ for more specific formatting.
For using this method, we can directly call it on a number and in return, we will get a string, which will be a representation of the currency with symbols and commas as thousands separators. Let’s understand it with the help of an example:
// Define a numeric value const number = 1234567890; // use the toLocaleString() method to format the number as currency(USD) const formattedNumber = number.toLocaleString('en-US', { style: 'currency', currency: 'USD', }); // Display the formatted number console.log(formattedNumber);
Output:
$1,234,567,890.00
3) Using Regular Expressions
Regular expressions, often referred to as regex, provide a powerful tool for identifying and manipulating patterns within strings.
By using regex, we can search for specific patterns in a string and replace them with the desired values. Here, regex can be used to add symbols and commas to format currency.
Here, we will create a function that will take a number and a currency symbol as arguments. Then, we will employ the replace() method of the string and provide a regex pattern to identify the positions where commas should be inserted.
We have to first convert the number to a string using tostring() method, following which we will use the pattern /\B(?=(\d{3})+(?!\d))/g in replace() method. This regex pattern is designed to identify positions where commas should be inserted, ensuring that they only appear between groups of three digits. See this example for more understanding:
// Define a function to format a number as currency using regex const byRegex = (number, symbol = '$') => { // Convert the number to a string and then use replace() with a regex pattern const formattedNumber = number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); // Format the number as a currency string return `${symbol}${formattedNumber}`; }; // Define a numeric value const number = 1234567890; // Display the result console.log(byRegex(number));
Regex is also used to do email validation in JavaScript.
Output:
$1,234,567,890.00
Conclusion
We have successfully covered three different approaches to formatting currency in JavaScript. This technique enhances user experience and improves the readability of currency information.