Convert a JavaScript Number Variable to a Currency Value with the Intl.NumberFormat Constructor
We can convert a JavaScript number variable to a currency value with the Intl.NumberFormat constructor.
For instance, we can write:
const formatter = new Intl.NumberFormat("en", {
style: "currency",
currency: "GBP"
});
console.log(formatter.format(1234.5));
to format 1234.5 into a currency value denominated in GBP.
We use the Intl.NumberFormat constructor with the locale as the first argument.
The 2nd argument is an object with some options.
The style is set to 'currency' to format it into a currency value.
And currency is set to 'GBP' to format it into British Pound.
Then we call formatter.format with the number to return the string with the currency value.
Therefore, the console log should log '£1,234.50' .