toLocaleString
The toLocaleString
function allows us (among other things) to be able to format numbers as currencies. This function will take care not only of displaying the symbol but also of positioning separators and cents.
Basic usage
const value = 200;
const price = value.toLocaleString(
"en-US", // local language
{
style: "currency", // function to apply
currency: "USD" // your preferred currency
}
);
console.log(price);
// $200.00
Another example
const value = 6000;
const price = value.toLocaleString(
"hi-IN",
{
style: "currency",
currency: "INR"
}
);
console.log(price);
// ₹6,000.00
Intl.NumberFormat
Suppose you need to apply the same formatting settings over and over again. In that case, you can create a function using the Intl.NumberFormat
constructor, which receives the settings and has methods to apply that format directly to numbers.
Basic usage
const value = 200;
const promoValue = 170.5;
const formatter = new Intl.NumberFormat(
"en-UK",
{
style: "currency",
currency: "GBP"
}
);
const price = formatter.format(value);
const promoPrice = formatter.format(promoValue);
console.log(price); // £200.00
console.log(promoPrice); // £170.50
How to find my country's currency and language?
To transform the number to a local string the first param of toLocaleString
and Intl.NumberFormat
is the language itself in ISO format followed by the country code.
Here is a list of languages in ISO format: https://datahub.io/core/language-codes
Top comments (1)
Excellent contribution. Thanks, Wilmer!