;

How to Format Number as Currency String in JavaScript


Tutorialsrack 14/03/2021 Javascript

In this article, you will learn how to format numbers as a Currency string in Javascript. A number, represented as monetary value, creates an impact and becomes much more readable, and that’s the reason behind formatting a number as currency. For example, let say you have a number more than 3 digits, then it should be displayed differently, let’s take a look at an example, 1000 displayed as $1,000.00 

Different countries have different conventions to display their currency in their locale. It is supported by all modern browsers now.

We can use the Intl.NumberFormat() method to format the number into any country’s currency in their locale format. This method takes the two parameters: the first parameter is locale such as en-US, en-IN, etc and the second parameter is options such as style, currency, useGrouping, maximumSignificantDigits, etc. 

The ‘en-US’ and ‘en-INR’ are used as the locale in the examples below, a list of all the locales can be found from here, and the currency used here is ‘INR’ and ‘USD’, but all the standard currencies are supported. Choosing a different locale and currency will format your monetary value according to their locale.

Examples of Format a number as a Currency String 

Example1: Format a Number as a Currency in US locale

In this example, we format a number as a currency in the US locale and the locale of the US is en-US and the US Currency is in $(dollar).

Example1: Format a Number as a Currency in US locale
const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2
})

console.log(formatter.format(1000)); //Output => "$1,000.00"
console.log(formatter.format(10)); //Output => "$10.00"
console.log(formatter.format(123233000)); //Output => "$123,233,000.00"

Example 2: Format a Number as a Currency in India locale

In this example, we format a number as a currency in the Indian locale and the locale of India is en-IN and the Indian Currency is in Indian Rupee.

Example 2: Format a Number as a Currency in India locale
const formatter = new Intl.NumberFormat('en-IN', {
  style: 'currency',
  currency: 'INR',
  minimumFractionDigits: 2
})

console.log(formatter.format(1000)); //Output => "₹1,000.00"
console.log(formatter.format(10)); //Output => "₹10.00"
console.log(formatter.format(123233000)); //Output => "₹12,32,33,000.00"

I hope this article will help you to understand how to format numbers as a Currency string in Javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags