获取区域设置的货币符号

时间:2018-06-01 20:18:11

标签: javascript locale currency symbols

如何获取给定货币字符串的货币符号(" GBP"," USD"等)?我提出的最好的东西看起来有点荒谬,有另一种方式还是我最好使用查找表?



const userLocale = "EN-gb";
const userCurrency = "GBP";
const withValueEl = document.querySelector(".withValue");
const withoutValueEl = document.querySelector(".withoutValue");
const valueWithCurrency = Number(0).toLocaleString(userLocale, {
  style: "currency",
  currency: userCurrency,
  minimumFractionDigits: 2
});
const valueWithoutCurrency = valueWithCurrency.replace(Number(0).toLocaleString(userLocale, {
  minimumFractionDigits: 2
}), "")

withValueEl.innerHTML = valueWithCurrency
withoutValueEl.innerHTML = valueWithoutCurrency

With value:<span class="withValue"></span><br /> Without value:<span class="withoutValue"></span><br />
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

Intnl.NumberFormat#formatToParts (MDN documentation)将返回格式化部分的数组,包括一个看起来像{ type: 'currency', value: '$' },的美元条目。

因此,您可以这样做:

const userLocale = "EN-gb";
const userCurrency = "GBP";
const withCurrency = new Intl.NumberFormat(userLocale, { style: 'currency', currency: userCurrency }).formatToParts(3.50).map(val => val.value).join('');
const withoutCurrency = new Intl.NumberFormat(userLocale, { style: 'currency', currency: userCurrency }).formatToParts(3.50).slice(1).map(val => val.value).join('');

并读取值:

> withCurrency
'£3.50'
> withoutCurrency
'3.50'

答案 1 :(得分:0)

这似乎比包含所有DOM选择器和值注入逻辑(与所需功能无关)的实际工作要多。提取符号非常简单:

const getCurrencySymbol = (locale, currency) => (0).toLocaleString(locale, { style: 'currency', currency, minimumFractionDigits: 0, maximumFractionDigits: 0 }).replace(/\d/g, '').trim()

或者如果您不使用es6:

function getCurrencySymbol (locale, currency) {
  return (0).toLocaleString(
    locale,
    {
      style: 'currency',
      currency: currency,
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    }
  ).replace(/\d/g, '').trim()
}

toLocaleString选项很冗长,因此没有太多要做。但是,您不需要使用Number构造函数(真的)。如果获得的货币值不带小数点或分隔符,则删除数字并仅保留符号就很简单。您将采用这种方法,因为根据语言环境和货币的不同,符号不一定总是单个字符。例如:

getCurrencySymbol('en-US', 'CNY') // CN¥
getCurrencySymbol('zh-CN', 'CNY') // ¥

修剪结果也是一个好主意。您可以像示例中那样将.trim()链接到结果,或更新正则表达式以包含空格。 应当指出,这是一种幼稚的方法,因为它仅适用于数字字符0-9。如果需要包括其他数字字符,例如阿拉伯(٠١٢٣٤٥٦٧٨٩),则需要更新正则表达式以包括unicode范围:/[0-9\u0660-\u0669]/g。您必须以类似的方式添加需要支持的任何其他号码系统。

本地化不是一个简单的问题,因此仅将货币代码用于this one这样的符号映射可能更有意义。