Search code examples
javascriptnumber-formatting

Intl.NumberFormat returns a result where number and currency symbol are divided through spacing


I just added a filter for my vue-app that is supposed to format a value as currency in EUR (German format).

This is the function:

app.config.globalProperties.$filters = {
    currency(value) {
        return new Intl.NumberFormat(process.env.MIX_LOCALE, { style: 'currency', currency: 'EUR' }).format(value);
    },
}

If I now do something like

{{$filters.currency(17.85)}}

I am getting this result: 17,85 €

As you can see, the value and the currency symbol are divided through a space. This is not quite what we are used to see in Germany, we would expect 17,85€.

As I did not find anything helpful in the docs to Intl.NumberFormat I am wondering if the removal of the space is even possible with Intl.NumberFormat.


Solution

  • My first reaction was, why not replace()? Then I saw the other answer's link. Then I tried it and the regex didn't work, the space was still there. So here's a working replace to fix the bug.

    app.config.globalProperties.$filters = {
        currency(value) {
            return new Intl.NumberFormat(
               process.env.MIX_LOCALE, 
               {style: 'currency', currency: 'EUR'})
               .format(value).replace(/\s/g,'');
        }
    }
    

    Testable snippet

    console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(1234567).replace(/\s/g,''));