获取区域设置的货币符号



如何获取给定货币字符串("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 />

当您包含所有 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-9u0660-u0669]/g。您必须以类似的方式添加需要支持的任何其他数字系统。

本地化是一个不平凡的问题,因此仅使用货币代码来符号映射可能更有意义。

不幸的是,我不知道直接获取货币符号的方法。

我能建议的是一个使用Intl.NumberFormat#formatToParts()。它提供涵盖格式化字符串每个部分的分段结果,因此可以通过编程方式对其进行检查,而无需猜测货币符号的位置:

const sym = (currency, locale) =>
new Intl.NumberFormat(locale, { style: 'currency', currency })
.formatToParts(1)
.find(x => x.type === "currency")
.value;
console.log(sym('EUR', 'de-DE'));

否则,尝试通过头寸或通过检查字符串来获取货币可能不起作用,因为货币符号可能位于不同位置:

const options = { style: 'currency', currency: "EUR" };
const us = new Intl.NumberFormat("en-US", options)
.format(1);
const de = new Intl.NumberFormat("de-DE", options)
.format(1);
console.log(us);
console.log(de);

或者一个代码可能有多个字母,而不仅仅是像墨西哥比索这样的单个符号:

const options = { style: 'currency', currency: "MXN" };
const mx = new Intl.NumberFormat("de-DE", options)
.format(1);
console.log(mx);


作为参考,有Intl.NumberFormat#resolvedOptions()将获取Intl.NumberFormat对象的已解析选项,但它不提供符号。只是可以传递给另一个格式化程序的选项:

const initialOptions = { style: 'currency', currency: "USD" };
const numberFormat1 = new Intl.NumberFormat('de-DE', initialOptions);
const options1 = numberFormat1.resolvedOptions();
//clone and change the currency:
const options2 = Object.assign({}, options1, {currency: "EUR"});
const numberFormat2 = new Intl.NumberFormat('de-DE', options2);
console.log(numberFormat1.format(1));
console.log(numberFormat2.format(1));

console.log(options1);
.as-console-wrapper { max-height: 100% !important; }

Intnl.NumberFormat#formatToParts

(MDN文档(将返回格式化部分的数组,包括一个看起来像美元{ 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'

只回答你的问题的标题。

const currencySymbol = (locale, currency) => {
const formatter = new Intl.NumberFormat(locale, {
style: 'currency',
currency,
});
let symbol;
formatter.formatToParts(0).forEach(({ type, value }) => {
if (type === 'currency') {
symbol = value;
}
});
return symbol;
};
console.log(currencySymbol('en-GB', 'GBP'), '   : Your example')
console.log(currencySymbol('zh', 'CNY'), '   : Yuan in China')
console.log(currencySymbol('en-US', 'CNY'), ' : Yuan in USA')
console.log(currencySymbol('en-US', 'USD'), '   : US Dollar in USA')
console.log(currencySymbol('zh', 'USD'), ' : US Dollar in China')

一些有用的参考资料...

  • ISO 语言代码参考
  • ISO 4217 货币代码参考

最新更新