Learn how to format any given number to a currency in javascript.
Many times you get value for something in numbers 5000
and you want to display them as a currency in your locale "₹ 5,000"
.
This is how your value would be displayed in INR.
Different countries have different formats to display the currency in their locale.
JavaScript has a very useful method for us with ECMAScript Internationalization API, a recent browser API which provides a lots of different internationalization features to format dates, times, currencies etc.
It is supported by all modern browsers now.
We can use the Intl.NumberFormat
method to format the number into any country’s currency.
Formatting number to INR currency
const toINR = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', minimumFractionDigits: 2 }); console.log(toINR.format(5000)); // "₹ 5,000.00" console.log(toINR.format(15)); // "₹ 15.00" console.log(toINR.format(6654987545)); // "₹ 6,65,49,87,545.00"
Intl.NumberFormat(locale,options)
as an input and returns a constructor. We then use this constructor to format any value.
currency: 'INR'
specifies the currency type and minimumFractionDigits: 2
specifies the count of numbers at decimal place.
You can update them to format the number to a currency of your choice.
Formatting number to USD currency
const toINR = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2 }); console.log(toINR.format(5000)); // "$5,000.00" console.log(toINR.format(15)); // "$15.00" console.log(toINR.format(6654987545)); // $6,654,987,545.00"
You can read about the different available options on MDN.