How to override the currency symbol used by Intl.NumberFormat

748 Views Asked by At

I am using the Intl.NumberFormat to format currencies on a web page, but I want to use specific currency symbols instead of the locale defined ones.

To be more specific, I want to show C$ for Canadian dollars, instead of the standard $, even though the locale is set to en-CA or fr-CA.

Example:

> Intl.NumberFormat('en-CA', { style: 'currency', currency: 'CAD' }).format(13999.59)
'$13,999.59'  // expected 'C$13,999.59'

> Intl.NumberFormat('fr-CA', { style: 'currency', currency: 'CAD' }).format(13999.59)
'13 999,59 $' // expected '13 999,59 C$'

I suppose there is a way to override the currency symbol, but I couldn't find how in the docs.

So, how can I override the currency symbol for a specific locale?

1

There are 1 best solutions below

1
Joshua Ooi On

Yes. It is possible with Intl.NumberFormat.prototype.formatToParts() method.

View the documentation here

const enCA = Intl.NumberFormat('en-CA', { style: 'currency', currency: 'CAD' }).formatToParts(13999.59).map(({ type, value }) => {
    switch (type) {
      case "currency":
        return `C$`;
      default:
        return value;
    }
  }).reduce((str, pt) => str + pt);
  
const frCA = Intl.NumberFormat('fr-CA', { style: 'currency', currency: 'CAD' }).formatToParts(13999.59).map(({ type, value }) => {
    switch (type) {
      case "currency":
        return `C$`;
      default:
        return value;
    }
  }).reduce((str, pt) => str + pt);

console.log(enCA);
console.log(frCA);