NumberFormat for CAD Currency not Right
Asked Answered
D

2

5

I am using Intl.NumberFormat and when I set the currency to CAD with an English locale, I am getting CA$5.00. I thought the symbols would be something $ or Can$ or C$ or CAD I just threw up a simple codepen https://codepen.io/jrock2004/pen/MMKqQq?editors=1010

const price = 5,
  locale = 'en-US',
  currency = 'CAD';

const formatter = new Intl.NumberFormat (locale, {
  style: 'currency',
  currency: currency,
});

const formattedPrice = formatter.format (price);

Am I doing something wrong or maybe nothing is wrong at all? Thanks

Devious answered 15/6, 2019 at 14:34 Comment(2)
What were you expecting? Notice that if you change the locale, the displayed formatted price changes. (try en-CA and fr-CA for instance)Dictaphone
I would of expected something like C$5.00 or Can$5.00. I notice that the format changes but I believe for CAD with en-US the format is wrongDevious
P
6

Javascript engine V8 uses ICU for currency(and other locale) formatting. And ICU uses CLDR. In cldr we have a list of defined alternative names here. So when we set locale as US(en_US) and we want us dollars then the symbol is $. But for the same locale we can get different dollars so in order to distinguish it CDLR returns different symbols. Same would be if you set locale to en_CA and currency to CAD then we get the symbol $ because Canadians refer to Canadian dollars as dollars(no surprise here :) ) And for locale = 'en-CA', currency = 'USD' we would get US$1.00.

There are several alternative dollar symbols in CLDR(AUD - A$, BRL - R$ and few others).

Also if we check the documentation for Intl.NumberFormat currencyDisplay options can be symbol, code or name. If you pass code you get CAD 1.00 and if you pass symbol you get CA$ 1.00.

TLDR; Js uses ICU that uses CDLR that returns CA$ for your case.

Purificator answered 15/6, 2019 at 20:58 Comment(2)
So to get C$100 what should I set for locale and currency? I set locale='en-CA' and currency='CAD' and I am getting $100 only. Thanks in advance .Ungraceful
I the moment i don't know if this is possible. if "CA$ 100" would be enough you could set the locale to 'en-US'Purificator
D
1

So to get c$100 I didn't find any direct solution but this helped me,

console.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'CAD', currencyDisplay: 'symbol' }).format(1000).replace('A', ''));
Depot answered 26/8, 2022 at 11:18 Comment(2)
This will do, thanks! I'm not quite sure why we're displaying C$ on our Canadian website which is presumably primarily for Canadians, who in turn just use $. Maybe our customers are just too nice to say anything? For what it's worth, I would call this the direct solution.Candescent
I would suggest changing the replace portion to .replace('CA$', 'C$'), so as to not interfere with other currencies, for those jet-set globetrotting enterprises out there.Candescent

© 2022 - 2024 — McMap. All rights reserved.