4

I am using this code to convert number to string:

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

I am getting the expexted output:

8,499

But same code is not working for Safari.

Please give me suggestion on same.........

phts
  • 3,889
  • 1
  • 19
  • 31
Preety Sapra
  • 615
  • 1
  • 6
  • 18

2 Answers2

0

Although toLocaleString (without parameters) works in all mainstream browsers, it's behaviour is inconsistent from one browser to another, unfortunately.

If consistent date/time formatting is important, I'm afraid you will need to resort to building your own version of toLocaleString or working with a library. Here are a couple that may be worth investigating:

kieranpotts
  • 1,510
  • 11
  • 8
0

I've encountered this issue today while working on a (almost complete) site which uses this function a lot and stumbled upon your question (Safari not showing any currency and/or thousands/decimal separators). I wrote a small override function to pop in and fix the toLocaleString to my needs (in Europe and euro's (€)).

Hope this helps anybody else encountering this same issue.

(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);

})();
Eric Mahieu
  • 327
  • 1
  • 6