toLocaleString() not supported in all browsers? [duplicate]

不想你离开。 提交于 2019-12-17 16:28:45

问题


i've this simple function:

Chrome, Firefox, 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?

is there any toLocaleString() replacement?


回答1:


The language spec leaves 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.

Different browsers are allowed to implement it differently, and can implement it differently based on the locale chosen by the user.




回答2:


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".

is there any toLocaleString() replacement?

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"


来源:https://stackoverflow.com/questions/16157762/tolocalestring-not-supported-in-all-browsers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!