toLocaleString() not supported in all browsers? [d

2019-01-24 07:39发布

问题:

This question already has an answer here:

  • Internationalization(Number formatting “num.toLocaleString()”) not working for chrome 4 answers

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"