我正在尝试使用 Intl 作为默认货币格式化程序,它几乎是完美的。
使用来自 Intl.NumberFormat() constructor 的示例:
const number = 123456.789;
console.log(new Intl.NumberFormat('de-DE', { style: 'currency',
currency: 'EUR' }).format(number)); // expected output: "123.456,79 €"
// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY'
}).format(number)); // expected output: "¥123,457"
这几乎是完美的,但我实际上想从输出中删除符号。所以我希望看到:// expected output: "123.456,79"
// expected output: "123,457"
我发现我花了一个多小时寻找解决方案却只发现了某种替换/trim 用法,这很奇怪。为什么没有选项可以使用所有 Intl 功能格式化数字,而只删除货币符号?!?
我希望我错过了,tbh。
最佳答案
实现您想要的一种简单方法是使用 String#replace()
从字符串中删除货币。为了使这更容易,您可以将 currencyDisplay
设置为 "code"
,它将使用 ISO 货币代码 - 与传递给 currency
的相同:
const number = 123456.789;
console.log(new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR',
currencyDisplay: "code"
})
.format(number)
.replace("EUR", "")
.trim()
); // 123.456,79
// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', {
style: 'currency',
currency: 'JPY',
currencyDisplay: "code"
})
.format(number)
.replace("JPY", "")
.trim()
); // 123,457
这可以提取到一个函数中:
const number = 123456.789;
console.log(format('de-DE', 'EUR', number)); // 123.456,79
console.log(format('ja-JP', 'JPY', number)); // 123,457
function format (locale, currency, number) {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency,
currencyDisplay: "code"
})
.format(number)
.replace(currency, "")
.trim();
}
允许您进行更多控制的另一种方法是使用
Intl.NumberFormat#formatToParts()
格式化数字但为您提供可以以编程方式使用和操作的 token 。例如,使用带有 locale = "de-DE"
和 currency = "EUR"
的方法,您将获得以下输出:[
{
"type": "integer",
"value": "123"
},
{
"type": "group",
"value": "."
},
{
"type": "integer",
"value": "456"
},
{
"type": "decimal",
"value": ","
},
{
"type": "fraction",
"value": "79"
},
{
"type": "literal",
"value": " "
},
{
"type": "currency",
"value": "EUR"
}
]
这意味着您可以轻松过滤掉 "type": "currency"
,然后将其余部分组合成一个字符串。例如:const number = 123456.789;
console.log(format('de-DE', 'EUR', number)); // 123.456,79
console.log(format('ja-JP', 'JPY', number)); // 123,457
function format (locale, currency, number) {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency,
currencyDisplay: "code"
})
.formatToParts(number)
.filter(x => x.type !== "currency")
.map(x => x.value)
.join("")
.trim()
}
关于javascript - 使用不带货币符号的 Intl.NumberFormat 进行货币格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68549027/