Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 524
Abdelouahab Pp Avatar asked Apr 22 '13 22:04

Abdelouahab Pp


2 Answers

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"
like image 154
Paul S. Avatar answered Nov 01 '22 17:11

Paul S.


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.

like image 39
Mike Samuel Avatar answered Nov 01 '22 17:11

Mike Samuel