0

I'm trying to add a comma between my 20000 to show as 20,000 without it messing up and have gotten pretty close but trying to fill in the next steps. Below, I've listed my code with the function thats able to do it but trying to connect the two together to properly work.

Here is my jsFiddle!

And code..

HTML

<span id="liveNumbers">23000</span>

JS

setInterval(function(){
random = (Math.floor((Math.random()*2)+1));
var plus = Math.random() < 0.5 ? 1 : 1;
random = random * plus; 
currentnumber = document.getElementById('liveNumbers');

document.getElementById('liveNumbers').innerHTML =  parseInt(currentnumber.innerHTML) + random;

 }, 3000);

function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
  val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return val;
  }
DoPeT
  • 299
  • 4
  • 16
  • 1
    Someone had same doubt as you http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – Olvathar Mar 18 '14 at 22:53
  • You should just be able to do something like `console.log(commaSeparateNumber(currentnumber))` and it should do what you're looking for – ntgCleaner Mar 18 '14 at 22:59

1 Answers1

3

You'd have to change your initial value to include a comma or do an initial run before the setInterval is started but something like this might work:

setInterval(function(){
   random = (Math.floor((Math.random()*2)+1));
   var plus = Math.random() < 0.5 ? 1 : 1;
   random = random * plus; 
   currentnumber = document.getElementById('liveNumbers');
   var curnum = parseInt(currentnumber.innerHTML.replace(",",""));

   document.getElementById('liveNumbers').innerHTML = 
       commaSeparateNumber(curnum + random);
}, 3000);

function commaSeparateNumber(val){
   while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
   }
   return val;
 }
malificent
  • 1,441
  • 14
  • 18