To convert a number to a specific currency format, we can use the NumberFormat
constructor function in the global Intl
object (Internationalization API).
/* Convert Number to a Currency */
const num = 12000;
const numberToCurrency = new Intl.NumberFormat("en-IN", {
style: "currency",
currency: "INR",
});
const currency = numberToCurrency.format(num);
Let's say you have the number 12000
,
// a number
const num = 12000;
Now let's convert this number into Indian currency format using the Intl.NumberFormat()
constructor function.
First, we have to create a currency converter like this,
// a number
const num = 12000;
// Create a new numberToCurrency Converter
const numberToCurrency = new Intl.NumberFormat();
The constructor function needs two optional arguments to convert the number into a formatted currency string.
-
The first argument is the
locale
of the currency. In our case, it isen-IN
for the Indian currency. For other currencies, you can check out this Stack overflow question. -
The second argument is an object representing the styles that need to be applied. For our use case, the object should have a key called
style
set tocurrency
, and another key calledcurrency
set to anISO 4217 currency code
. For our case since we need the currency to be in Indian format, the code isINR
.
So the object looks like this,
{style: 'currency', currency: 'INR'}
It can be done like this,
// a number
const num = 12000;
// Create a new numberToCurrency Converter
// Argument 1: Set the locale to en-IN
// Argument 2: Object representing styles to be applied
const numberToCurrency = new Intl.NumberFormat("en-IN", {
style: "currency",
currency: "INR",
});
Now we need to invoke the format()
method in the numberToCurrency
converter and pass the number as an argument to the method like this,
// a number
const num = 12000;
// Create a new numberToCurrency Converter
// Argument 1: Set the locale to en_IN
// Argument 2: Object representing styles to be applied
const numberToCurrency = new Intl.NumberFormat("en-IN", {
style: "currency",
currency: "INR",
});
// Use the format() method on the converter
// and pass the number as argument
const currency = numberToCurrency.format(num);
console.log(currency); // ₹12,000.00
That's all there is to it to convert a number to a currency format 😃.
See this example live in JSBin.