最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Currency Code to locale JS - Stack Overflow

programmeradmin2浏览0评论

Humour me here, but I have a trivial task of taking a number input, and format it to a currency code.

IE:

var value = 1000;
value.toLocaleString('en-AU, {
    style: 'currency',
    currency: 'AUD;,
    minimumFractionDigits: 2
});
// A$1,000.00

Which works - only problem is, this sits in a function, where I pass the value and the currency..

function(value, currency)

Which now I have to maintain a list of currency to locale mappings. Is there a quick and lightweight way to format a number to currency. Im quite happy to sent a locale instead of the currency. Either way, I don't want to maintain two lists.

Humour me here, but I have a trivial task of taking a number input, and format it to a currency code.

IE:

var value = 1000;
value.toLocaleString('en-AU, {
    style: 'currency',
    currency: 'AUD;,
    minimumFractionDigits: 2
});
// A$1,000.00

Which works - only problem is, this sits in a function, where I pass the value and the currency..

function(value, currency)

Which now I have to maintain a list of currency to locale mappings. Is there a quick and lightweight way to format a number to currency. Im quite happy to sent a locale instead of the currency. Either way, I don't want to maintain two lists.

Share Improve this question asked Jan 28, 2016 at 1:09 Marais RossouwMarais Rossouw 9571 gold badge11 silver badges29 bronze badges 2
  • Possible duplicate of Where should I put the json result in money.js? – Paul Sweatte Commented Jul 27, 2016 at 17:34
  • @PaulSweatte not exactly... Im not concerned about currency conversion with relation to exchange rates.. It was more in relation to getting the local from a currency code, so <input>AUD => <output>en-AU – Marais Rossouw Commented Jul 27, 2016 at 23:58
Add a ment  | 

3 Answers 3

Reset to default 4

If what you want is where to get the list of equivalences, I didn't found one, but you could build it matching these lists

currencies (find "ISO 4217 - Currency Code Maintenance: Get the Correct Currency Code"): https://www.six-group./en/products-services/financial-information/data-standards.html

locales: http://www.science.co.il/Language/Locale-codes.asp

You don't need two lists. Just have a map (object), using the currency as the key, and the locale as the value.

var currencyToLocale = {
  'AUD': 'en-AU'
    // etc...
};

function formatAsCurrency(value, currency) {
  // get the locale from the map...
  var locale = currencyToLocale[currency];

  return value.toLocaleString(locale, {
    style: 'currency',
    currency: currency,
    minimumFractionDigits: 2
  });
};

console.log(formatAsCurrency(1000, 'AUD'));

return new Intl.NumberFormat(locale, { style: 'currency', currency: currencyCode }).format(value)
发布评论

评论列表(0)

  1. 暂无评论