The Intl.NumberFormat() constructor creates an object for formatting numbers based on locale-specific rules, making output readable and region-friendly.
- It supports formatting styles like decimal, currency, percent, and unit.
- Locale and options control symbols, separators, and display style.
- It can be called with or without new, and both create a new formatter instance.
Syntax:
new Intl.NumberFormat()
new Intl.NumberFormat([locales[, options]])Parameters:
- Locales: It contains a String or an array of Strings that allow the following value.
- num: It specifies the numbering system to be used which can be arab, bali, latn, tibt etc.
- Options: It is an object which can have properties like compactDisplay, currency,currencyDisplay, currencySign ,style, unit,unitDisplay, etc.
Return value: It return a new Intl.NumberFormat object.
Example 1: In this example, we will use the basic use of Intl.NumberFormat() constructor.
let amount = 10000;
let newAmount = new Intl.NumberFormat().format(amount)
console.log(newAmount);
Output:
10,000Example 2: In this example, we will perform Decimal and percentage formatting with the help of Intl.NumberFormat() constructor.
let amount = 2000;
let newAmount1 = new Intl.NumberFormat('en-US',
{ style: 'decimal' }).format(amount);
let newAmount2 = new Intl.NumberFormat('en-US',
{ style: 'percent' }).format(amount);
console.log(newAmount1);
console.log(newAmount2);
Output:
2,000
200,000%Example 3: In this example, we will perform unit formatting and currency formatting with the help of Intl.NumberFormat() constructor.
let num = 5000;
// Unit formatting
let num1 = new Intl.NumberFormat('en-US',
{ style: 'unit', unit: 'liter' }).format(num);
let num2 = new Intl.NumberFormat('en-US',
{
style: 'unit',
unit: 'liter',
unitDisplay: 'long'
}).format(num);
// Currancy formatting
let currency = 50;
let newCurrency = new Intl.NumberFormat('en-US',
{
style: 'currency',
currency: 'USD'
}).format(currency);
console.log(num1);
console.log(num2);
console.log(newCurrency);