toLocaleString 不适用于所有浏览器中小于 10000 的数字

toLocaleString not working on numbers less than 10000 in all browsers

我正在开发一个根据用户配置显示数字的应用程序。一切都按预期工作,除非我在 Chrome 中尝试使用小于 10000 的数字,并使用以下语言环境:"es-AR"。有什么想法吗?

Chrome:

火狐:

边缘:

console.log( (10000).toLocaleString("es-AR") );
console.log( (9999).toLocaleString("es-AR") );
console.log( (9999).toLocaleString("en-US") );

根据最新的 CLDR 数据,这是西班牙语言环境的预期行为。具体来说 "Minimum Grouping Digits" 设置为 2 according to the CLDR survey tool.

这意味着 the grouping separator is only used when there would be 2 or more digits before it.

显然 Firefox 和 Edge 使用该数据的旧版本或者尚不支持该字段。

该功能已引入 in CLDR 26, which was released in 2014,但像这样的增强功能需要相当长的时间才能通过软件堆栈。

根据 CLDR,西班牙西班牙语的最小分组位数确实是两位。

可在 GitHub 中找到完整的语言规范。

有趣的是,始终使用至少两个分组数字 与 RAE 规则冲突 。他们声明此建议并不适用于所有情况,将会计和可能涉及安全风险的任何情况作为特定例外提及。

鉴于规范强制执行此行为,并且 real-life 经验是有时将此报告为需要修复的错误,这里是原始发布者要求的简单解决方法。它就像检测四个整数数字并手动添加千位分隔符一样肮脏(并且可以通过许多更好的方法来完成)。

var decimals=2;

value=value.toLocaleString('es', {minimumFractionDigits: decimals, maximumFractionDigits: decimals});

//fix spanish thousands separator for <10.000
if(value.indexOf(',')==4 || (decimals==0 && value.length==4)){
    value=value.substr(0,1)+'.'+value.substr(1);
}