Format a number as currency in JS

We can to this with Intl or with localeCompare, and both solutions are easy to implement

By: Ajdin Imsirovic 13 January 2021

This easy exercise shows two simple ways to format a number as currency in vanilla JavaScript.

A comma character on a yellow-painted wall

Let’s say we want to display a number as currency. For example, we want to format the number 99.99 so that it looks like this: $99.99.

To make this change to our number, we’ll use the Intl object again.

1
2
3
4
new Intl.NumberFormat('en-GB', {
    style: 'currency',
    currency: 'EUR'
}).format(99.99);

We can now save this object in a variable:

1
2
3
4
const displayAsCurrency = new Intl.NumberFormat('en-GB', {
  style: 'currency',
  currency: 'EUR',
});

And now we can run the format() method:

1
displayAsCurrency.format(99.99); // "€99.99"

Another solution is to use the toLocaleString() method:

1
2
3
4
5
6
7
(99.99).toLocaleString('en-GB', 
    { style: 'currency', 
      currency: 'EUR', 
      minimumFractionDigits: 3 
    }
);
// returns: "€99.990"



Note:
This exercise comes from Book 3 of my book series on JS, available on Leanpub.com.



Feel free to check out my work here: