在我的应用程序中,有几个地方需要用户输入货币值。该应用程序支持以多种货币和本地化方式存储这些货币值(value)。
我正在使用 Intl.NumberFormat Javascript 中的对象将数字格式化为我需要的任何货币和语言环境,但无法使用它取消格式化数字。
到目前为止,我发现的所有库都要求您提供小数点和千位分隔符,以便格式化/取消格式化功能起作用。但是,我需要一种方法来首先找到小数点和千位分隔符,所以我不能使用它们。
如何可靠地获取当前语言环境的小数点分隔符?
最佳答案
选项 1: 使用 Intl.NumberFormat#formatToParts
最可靠的方法,仅适用于 browsers supporting the Intl API .否则它需要 Intl polyfill
function getDecimalSeparator(locale) {
const numberWithDecimalSeparator = 1.1;
return Intl.NumberFormat(locale)
.formatToParts(numberWithDecimalSeparator)
.find(part => part.type === 'decimal')
.value;
}
选项 2: 使用 toLocaleString
不太优雅,它依赖于分隔符总是一个字符长的事实,这似乎对所有语言都是如此:Decimal separator - Wikipedia
function getDecimalSeparator(locale) {
const numberWithDecimalSeparator = 1.1;
return numberWithDecimalSeparator
.toLocaleString(locale)
.substring(1, 2);
}
此处已建议:With a browser, how do I know which decimal separator that the client is using?
示例:
> getDecimalSeparator()
"."
> getDecimalSeparator('fr-FR')
","
选项 1 的好处:
我们可以扩展它来检索给定语言环境的decimal 或group 分隔符:
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 - 如何在 Javascript 中找到当前语言环境的小数点分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33159354/