jQuery counter insert commas to break up string

272 views Asked by At

I have a counter that increments every x seconds, here's my code:

var counter=22000000000;
if(typeof(localStorage.getItem('counts'))!='object') {
   counter=parseInt(localStorage.getItem('counts'));
}
$(".count").html(counter);
setInterval(function () {
    $(".count").html(counter);
    ++counter;
    localStorage.setItem('counts',counter);
}, 18000);

Because the starting number is so high it doesn't read well, see it here: http://jsfiddle.net/vpju4cpr/1/

Ideally instead of outputting 22000000000 I'd like it to read 22,000,000,000

How can I do this?

2

There are 2 answers

0
Jameson the dog On BEST ANSWER

in your .html() function, change counter to counter.toLocaleString() like this:

var counter=22000000000;
 if(typeof(localStorage.getItem('counts'))!='object') {
    counter=parseInt(localStorage.getItem('counts'));
 }
 $(".count").html(counter.toLocaleString());
 setInterval(function () {
     $(".count").html(counter.toLocaleString());
     ++counter;
     localStorage.setItem('counts',counter);
 }, 18000);

0
TaoPR On

To format a number with comma, you can use this regex:

var counterString = counter.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
$(".count").html(counterString );

input: 199999999

output: "199,999,999"