You can use the function toLocaleString
or Intl.NumberFormat
to get a formatted currency string from the
JavaScript number. Here’s how it works.
In the most basic case you can just call the function toLocaleString
on the number that you’d like to format.
const salary = 7000;
const formattedSalary = salary.toLocaleString('en-US', {style: 'currency',currency: 'USD'});
console.log(formattedSalary); // $7,000.00
You can also use Intl.NumberFormat
. It works very similarly, however in this case you first construct a formatter,
and then format the number by calling the format
function.
const salary = 10000;
const formattedSalary = Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD'})
.format(salary);
console.log(formattedSalary); // $10,000.00
Try it with other currencies by changing the currency code!