Search code examples
javascriptcounterseparator

Thousand separator in a JavaScript counter


I have this counter JavaScript snippet:

var START_DATE = new Date("October 24, 2015 11:00:00"); // start
var INTERVAL = 1; // sec
var START_VALUE = 0; // init value
var INCREMENT = 0.13; // value per sec
var count = 0;

window.onload = function()
{
 var msInterval = INTERVAL * 1000;
 var now = new Date();

 count = parseInt((now - START_DATE)/msInterval,10) * INCREMENT + START_VALUE;
 document.getElementById('count').innerHTML = count.toFixed(2);
 setInterval("count += INCREMENT; document.getElementById('count').innerHTML = count.toFixed(2);", msInterval);    
}

The counter may eventually display values in thousands and millions. My question is how to separate the thousands with a comma/blank space? I tried to achieve this via CSS, but apparently the options available here are not very practical. I was wondering on a possible solution in JavaScript. I found this on jsfiddle, but I am not sure how to apply it on the result of the counter?

function addCommas(n){
var rx=  /(\d+)(\d{3})/;
return String(n).replace(/^\d+/, function(w){
    while(rx.test(w)){
        w= w.replace(rx, '$1,$2');
    }
    return w;
});
}

Solution

  • You can use javascript's built in toLocaleString function. Here is an example from MDN

    var number = 3500;
    
    console.log(number.toLocaleString()); // Displays "3,500" if in U.S. English locale
    

    There are some additional options you can use with that function, but they are not all supported by various browsers. Basic use should work though.