Format numbers as currency strings in JavaScript
In this tutorial, I will show you how to format numbers as currency strings in JavaScript. The currency strings represent numbers in a specific currency format. The currency symbol, like “$” for USD, and the appropriate number of decimal places are included in this format. For example, a currency string for the number 1200 in USD will be “$1,200.00“.
We can do this in multiple ways like below.
Using the Intl.NumberFormat object
We can use the Intl.NumberFormat constructor to formate language-sensitive numbers. We will use this constructor to format numbers as currency strings.
const formatCurrency = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
console.log(formatCurrency.format(32000));In the above program, the Intl.NumberFormat() constructor creates a new number formatting object with the locale set to en-US, the style set to currency and the currency which is set to USD.
Then the format() method formats the number as a currency value in the specified locale and currency.
Output:
$32,000.00
Using the toLocaleString() method
The toLocaleString() method returns a string that represents the number in the specified language. Here is an example below to format numbers as currency strings using this method.
const formatCurrency = (32000).toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
});
console.log(formatCurrency);In the above program, I have declared a variable formatCurrency and assigned the result of calling the toLocaleString() method on the number 32000 to that variable.
Then the toLocaleString() method is used to format a number as a string, using the specified locale, style, and currency.
Output:
$32,000.00
Using the ‘+’ operator
The + operator is used for both addition and concatenation, it combines two strings and returns a new string.
const formatCurrency = 3254.1569;
console.log('$ ' + formatCurrency.toFixed(2));In the above program, I have declared a variable formatCurrency with the value 3254.1569.
Then I used toFixed() method and passed 2 as its argument that rounds the number into 2 decimal places.
The result will concatenate with the string $ and log into the console.
Output:
$ 3254.16
Using replace() method including RegEx
We can use replace() method including regular expressions (RegEx) to format a number as a currency string.
const num = 3254.1569;
const formatCurrency = num.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
console.log('$ ' + formatCurrency)In the above program, the replace() method is used to add commas as thousands of separators.
Then I used regular expressions in the replace method to find all the digits before the decimal and add the comma at the correct position.
Output:
$ 3,254.16
Leave a Reply