Alternative toLocaleString () for Safari browser

I am using this code to convert number to string:

ProductsData[0]['price'].toLocaleString();

      

I am getting expexted output:

8,499

      

But the same code doesn't work for Safari .

Please give me a suggestion on the same .........

+3


source to share


2 answers


While toLocaleString

(no parameters) works in all major browsers, this behavior is unfortunately incompatible from one browser to another.

If consistent date and time formatting is important, I'm afraid you will have to resort to creating your own version toLocaleString

or working with a library. Here are a couple that might be worth exploring:



0


source


I ran into this issue today while working on a (almost complete) site that uses this feature a lot and came across your question (Safari doesn't show any currency and / or thousand / decimal separators). I wrote a little override function to go into it and fix toLocaleString for my needs (in Europe and Euro (€)).

Hope this helps someone else to face this same problem.



(function() {
    Number.prototype._toLocaleString = Number.prototype.toLocaleString;
    Number.prototype.toLocaleString = function(locales,options) {
        if(options.style == "currency") {     // only format currencies.
            var prepend = "";
            if(options.currency == "EUR") {
            prepend = "\u20AC ";     // unicode for euro.
            }
            var val = this;
            val = val;
            
            // check if the toLocaleString really does nothing (ie Safari)
            
            var tempValue = val._toLocaleString(locales,options);
            if(tempValue == val.toString()) { // "broken"
            return prepend+val.formatMoney(2); // <-- our own formatting function.
            } else {
            return tempValue;
            }
        } else {
        return this._toLocaleString(locales,options);
        }
    };
    
    Number.prototype.formatMoney = function(c, d, t){
    var n = this, 
    c = isNaN(c = Math.abs(c)) ? 2 : c, 
    d = d == undefined ? "," : d, 
    t = t == undefined ? "." : t, 
    s = n < 0 ? "-" : "", 
    i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), 
    j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
     };
   
    // demonstration code
    var amount = 1250.75;
    var formattedAmount = amount.toLocaleString('nl-NL', {style:'currency',currency: 'EUR'});
    console.log(formattedAmount);

})();
      

Run codeHide result


0


source







All Articles