javascript 并非所有浏览器都支持 toLocaleString()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16157762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
toLocaleString() not supported in all browsers?
提问by Abdelouahab Pp
i've this simple function:
我有这个简单的功能:
Chrome, Firefox, IE:
铬、火狐、IE:
Number(1000000).toLocaleString()
"1 000 000" // in french system, the space is the separator instead of the comma
Opera, Maxthon:
歌剧、傲游:
Number(1000000).toLocaleString()
"1000000"
why Opera and Maxthon cant format it? they support this method but dont execute it in the right way?
为什么Opera和Maxthon不能格式化?他们支持这种方法,但没有以正确的方式执行它?
is there any toLocaleString()
replacement?
有toLocaleString()
替代品吗?
采纳答案by Mike Samuel
The language specleaves the definition very open-ended:
该语言规范叶子的定义非常开放式的:
15.7.4.3
Number.prototype.toLocaleString()
Produces a String value that represents this Number value formatted according to the conventions of the host environment's current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.
15.7.4.3
Number.prototype.toLocaleString()
生成一个 String 值,该值表示根据主机环境当前区域设置的约定格式化的此 Number 值。这个函数是依赖于实现的,允许但不鼓励它返回与 toString 相同的东西。
Different browsers are allowed to implement it differently, and can implement it differently based on the locale chosen by the user.
允许不同的浏览器以不同的方式实现它,并且可以根据用户选择的区域设置不同地实现它。
回答by Paul S.
The output will also be different depending on the user's locale settings, even if Number.prototype.toLocaleString
is supported by their browser, e.g. for me on en-GB, Number(1000000).toLocaleString();
gives me "1,000,000"
.
根据用户的区域设置,输出也会有所不同,即使Number.prototype.toLocaleString
他们的浏览器支持,例如对于我来说en-GB,Number(1000000).toLocaleString();
给我"1,000,000"
.
is there any
toLocaleString()
replacement?
有
toLocaleString()
替代品吗?
Why not write one to do exactly what you want? For example,
为什么不写一个来做你想做的事呢?例如,
function localeString(x, sep, grp) {
var sx = (''+x).split('.'), s = '', i, j;
sep || (sep = ' '); // default seperator
grp || grp === 0 || (grp = 3); // default grouping
i = sx[0].length;
while (i > grp) {
j = i - grp;
s = sep + sx[0].slice(j, i) + s;
i = j;
}
s = sx[0].slice(0, i) + s;
sx[0] = s;
return sx.join('.');
}
Now
现在
localeString(1000000.00001);
// "1 000 000.00001"