简体   繁体   中英

NumberFormat for CAD Currency not Right

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

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.

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', ''));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM