选项 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')
" "