The Intl.NumberFormat object can be used to format a number as a currency in Javascript. Various options can be set to customize format of currency code, comma / decimal separators etc.
A number in Javascript can be displayed in currency format using the Intl.NumberFormat object. Furthermore currency is formatted as per the required localization.
Creating a new Intl.NumberFormat object needs 2 parameters :
- First parameter is a string representing a valid language tag, such as "en-US", "en-IN", "de-DE", "fr-FR" etc.
- Second parameter is an object containing options :
- style : To display the number as currency, this needs to be set as currency.
- currency : A valid currency code needs to be passed here, such as "USD", "EUR" etc.
- currencyDisplay : This represents the format in which we want the currency to be displayed. It can have 3 values :
symbol — to display currency symbol, such as "$", "€" etc. This is the default.
code — to display currency code, such as "USD", "EUR" etc.
name — to display localized currency name, such as "dollar", "euro" etc. - useGrouping : A boolean true groups the currency as thousands or thousand/lakh/crore. Value of false does no grouping. The default is true.
- minimumFractionDigits : By default, the minimum fraction digits are set as per the currency code. However this can be explicitly set by passing the required minimum fraction digits to show.
- maximumFractionDigits : By default, the maximum fraction digits are set as per the currency. However this can be explicitly set by passing the required maximum fraction digits to show.
Using Intl.NumberFormat is explained through some examples below.
var x = 6565588.689;
var currency = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(x);
// "$6,565,588.69"
console.log(currency);
var x = 6565588.689;
var currency = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(x);
// "₹ 65,65,588.69"
console.log(currency);
var x = 6565588.689;
var currency = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(x);
// "6.565.588,69 €"
console.log(currency);
var x = 6565588.689;
var currency = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', currencyDisplay: 'code', useGrouping: false }).format(x);
// "USD 6565588.69"
console.log(currency);
var x = 6565588.689;
var currency = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', currencyDisplay: 'name' }).format(x);
// "65,65,588.69 Indian rupees"
console.log(currency);
var x = 6565588;
var currency = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', useGrouping: false, minimumFractionDigits: 0 }).format(x);
// "$6565588"
console.log(currency);