/

How to Format a Number as a Currency Value in JavaScript

How to Format a Number as a Currency Value in JavaScript

In this blog post, we will learn how to convert a number into a currency value using the JavaScript Internationalization API. By the end, you will be able to effortlessly transform numbers into currency formats based on different countries’ conventions.

Let’s start with a simple example: suppose we have a number, 10, which represents the price of something. We want to display it as $10.00 in USD.

However, if the number has more than 3 digits, the format should be different. For instance, 1000 should be displayed as $1,000.00.

To achieve this, we can utilize the ECMAScript Internationalization API, which is a browser API that provides various internationalization features such as date and time formatting. Fortunately, this API is widely supported by modern browsers.

Here’s an example of how to use the Intl.NumberFormat constructor to format numbers as currency values:

1
2
3
4
5
6
7
8
9
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
});

formatter.format(1000); // "$1,000.00"
formatter.format(10); // "$10.00"
formatter.format(123233000); // "$123,233,000.00"

In this code snippet, we create a number formatter using the Intl.NumberFormat constructor. The en-US parameter specifies the locale, which represents the language and country combination (in this case, English speakers in the United States). Additionally, we set the style to 'currency' and the currency to 'USD' to format the numbers as USD currency values. The minimumFractionDigits property is used to ensure that the fraction part always has at least 2 digits.

You can refer to the NumberFormat MDN page to explore other parameters and options available for formatting numbers.

If you want to format the numbers as a different currency or for a specific country, you can modify the constructor parameters accordingly. Here’s an example for formatting numbers as Euro currency values for Italy:

1
2
3
4
const formatter = new Intl.NumberFormat('it-IT', {
style: 'currency',
currency: 'EUR'
});

By using the ECMAScript Internationalization API, you can easily format numbers as currency values in JavaScript, catering to different conventions based on countries and languages.

Tags: JavaScript, number formatting, currency formatting, Internationalization API