admin管理员组

文章数量:1333210

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

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

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

Share Improve this question asked Jun 15, 2019 at 14:34 jrock2004jrock2004 3,5117 gold badges48 silver badges85 bronze badges 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) – Félix Paradis Commented Jun 15, 2019 at 15:21
  • 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 wrong – jrock2004 Commented Jun 15, 2019 at 19:35
Add a ment  | 

2 Answers 2

Reset to default 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.

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

本文标签: javascriptNumberFormat for CAD Currency not RightStack Overflow