Use Intl.NumberFormat number formatter (part of the Internationalization API) to format numbers as currency strings in JavaScript. This method formats numbers using custom locale parameters.
The Intl.NumberFormat()
constructor accepts two arguments, the first being a locale string, with which we define the locale we want to format to:
const price = 1500000.15;
let US = Intl.NumberFormat('en-US');
let IN = Intl.NumberFormat('en-IN');
console.log("US Locale: " + US.format(price));
console.log("Indian Locale: " + IN.format(price));
Output: US Locale: 1,500,000.15
Indian Locale: 15,00,000.15
The second argument can be used to specify the options you want to apply while formatting.
style
currency
useGrouping
maximumSignificantDigits
Example format number as currency in JavaScript
Simple HTML example code.
<!DOCTYPE html>
<body>
<script>
// Create our number formatter.
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
var res = formatter.format(2500);
console.log(res)
</script>
</body>
</html>
Output:
Here is the format of price
into different currencies:
const price = 1500000.15;
// Format the price above to USD, INR, EUR using their locales.
let dollarUS = Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
});
let rupeeIndian = Intl.NumberFormat("en-IN", {
style: "currency",
currency: "INR",
});
let euroGerman = Intl.NumberFormat("de-DE", {
style: "currency",
currency: "EUR",
});
console.log("Dollars: " + dollarUS.format(price));
// Dollars: $147,000,000.15
console.log("Rupees: " + rupeeIndian.format(price));
// Rupees: ₹14,70,000.15
console.log("Euros: " + euroEU.format(price));
// Euros: 1.470.000,15 €
Do comment if you have any doubts or suggestions on this JS format code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version