-3

I am trying to print a number with two decimal places, and I need it with dots as thousands separators.

I can't use .toLocaleString(), since it won't work in Safari...

Here's my code:

var currentTime;

    if (localStorage['time']) { 
        currentTime = Number.parseFloat(localStorage['time']); 
    } 
    else {
        currentTime = 0; 
    }

    var container = document.getElementById('count'); 

    setInterval(function() {
        currentTime += .01; 
        container.innerHTML = currentTime.toFixed(2);
        //container.innerHTML = currentTime.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}); 
        localStorage['time'] = currentTime; 
    }, 100); 
tmthydvnprt
  • 10,398
  • 8
  • 52
  • 72
Giovana
  • 1
  • 1
  • There is an in-depth answer to this common question here http://stackoverflow.com/a/149099/280842 – filype Jul 29 '16 at 22:25
  • Possible duplicate of [How can I format numbers as money in JavaScript?](http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript) – jmoerdyk Jul 29 '16 at 22:29

1 Answers1

0

You can use this snippet which works in most cases:

// source: http://stackoverflow.com/a/149099/280842
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 = parseInt(n = Math.abs(+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) : "");
 };

use it as:

(123456789.12345).formatMoney(2, '.', ',');

Working example: https://jsbin.com/nuyinatuju/edit?js,console

filype
  • 8,034
  • 10
  • 40
  • 66