0

I've tried everything I can find online about this but they all seem to deal with static numbers, not animated numbers.

Is it possible to have commas added to my values as the number increases using this by modifying this function?

$('.counter').each(function() {
        var $this = $(this),
            countTo = $this.attr('data-count');

        $({ countNum: $this.text()}).animate({
            countNum: countTo
        },

        {

        duration: 500,
        easing:'linear',
        step: function() {
            $this.text(Math.floor(this.countNum));
        },
        complete: function() {
            $this.text(this.countNum);
              //alert('finished');
        }

    }); 
Machavity
  • 30,841
  • 27
  • 92
  • 100
JSum
  • 597
  • 9
  • 20

2 Answers2

8

Just add the commas wherever you're currently setting the element text().

Comma code lifted from add commas to a number in jQuery

$('.counter').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count');

  $({
    countNum: $this.text()
  }).animate({
      countNum: countTo
    },

    {
      duration: 5000,
      easing: 'linear',
      step: function() {
        $this.text(commaSeparateNumber(Math.floor(this.countNum)));
      },
      complete: function() {
        $this.text(commaSeparateNumber(this.countNum));
        //alert('finished');
      }
    }
  );

});

function commaSeparateNumber(val) {
  while (/(\d+)(\d{3})/.test(val.toString())) {
    val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
  }
  return val;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="counter" data-count="1000000"></span>
Community
  • 1
  • 1
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
5

Use parseFloat in case of string contain comma. please check the below working code

$('.counter').each(function() {
    $(this).prop('Counter', 0).animate({
        Counter: parseFloat($(this).text().replace(/,/g, ''))
    }, {
        duration: 10000,
        easing: 'swing',
        step: function(now) {
            $(this).text(getRupeesFormat(Math.ceil(now)));
        }
    });
});


function getRupeesFormat(val) {
    while (/(\d+)(\d{3})/.test(val.toString())) {
        val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
    }
    return val;
}
Soubhagya Kumar Barik
  • 1,979
  • 20
  • 26