如何在Javascript中找到当前语言环境的小数点分隔符 [英] How do I find the decimal separator for current locale in Javascript
问题描述
在我的应用程序中,有几个地方需要用户输入货币值.该应用程序支持以多种货币以及本地化存储这些货币值.
In my application there are several places where the user is expected to enter a monetary value. The application supports storing these monetary values in multiple currencies as well as localization.
我正在使用 Intl.NumberFormat Javascript中的对象可以将数字格式化为我需要的任何货币和语言环境,但是无法使用该数字对数字进行格式化.
I'm using the Intl.NumberFormat object in Javascript to format a number into any currency and locale I need, but there's no way to unformat the number using that.
到目前为止,我发现的所有库都要求您提供小数和千位分隔符,以便格式化/取消格式化功能起作用.但是,我需要一种方法来首先查找小数和千位分隔符,以便不能使用它们.
All of the libraries I've found so far require you to provide the decimal and thousands separators in order for the formatting/unformatting functions to work. However, I need a way to find what the decimal and thousands separators are in the first place so I can't use those.
如何可靠地获取当前语言环境的小数点分隔符?
How can I reliably get the decimal separator for the current locale?
推荐答案
选项1:使用 Intl.NumberFormat#formatToParts
最可靠的方法,仅适用于支持Intl API的浏览器.否则,它需要国际polyfill
Most reliable method, only works for browsers supporting the Intl API. Otherwise it requires an Intl polyfill
function getDecimalSeparator(locale) {
const numberWithDecimalSeparator = 1.1;
return Intl.NumberFormat(locale)
.formatToParts(numberWithDecimalSeparator)
.find(part => part.type === 'decimal')
.value;
}
选项2:使用 toLocaleString
不太优雅,它依赖于一个分隔符总是一个字符长的事实,所有语言似乎都是这样:小数点分隔符-维基百科
Less elegant, it relies on the fact that a separator is always one character long, which seems to be the case for all languages: Decimal separator - Wikipedia
function getDecimalSeparator(locale) {
const numberWithDecimalSeparator = 1.1;
return numberWithDecimalSeparator
.toLocaleString(locale)
.substring(1, 2);
}
这已在此处建议: 示例:
> getDecimalSeparator()
"."
> getDecimalSeparator('fr-FR')
","
选项1的奖励:
我们可以扩展它以检索给定语言环境的十进制或 group 分隔符:
We could extend it to retrieve either the decimal or group separator of a given locale:
function getSeparator(locale, separatorType) {
const numberWithGroupAndDecimalSeparator = 1000.1;
return Intl.NumberFormat(locale)
.formatToParts(numberWithGroupAndDecimalSeparator)
.find(part => part.type === separatorType)
.value;
}
示例:
> getSeparator('en-US', 'decimal')
"."
> getSeparator('en-US', 'group')
","
> getSeparator('fr-FR', 'decimal')
","
> getSeparator('fr-FR', 'group')
" "
这篇关于如何在Javascript中找到当前语言环境的小数点分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!