0

How would I modify the following to include commas in the output? For example output of 300000 would print as `300,000'?

the html

<span class="number counter" data-count="300000">300,000</span>

the magic:

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


        $({countNum: $this.text()}).animate({
                countNum: countTo
            },
            {
                duration: 999,
                easing:'linear',
                step: function() {
                    $this.text(Math.floor(this.countNum));
                },
                complete: function() {
                    $this.text(addCommas(this.countNum));
                    console.log('finished')
                }
            });

        function addCommas(nStr){
            //return comma
        }
    });
});

This is different from - How do I format numbers using JavaScript? - because I need to countup and display counter with comma - the action during step is what requires dynamic comma being added.

Zach Smith
  • 5,490
  • 26
  • 84
  • 139
  • Possible duplicate of [How do I format numbers using JavaScript?](https://stackoverflow.com/questions/5731193/how-do-i-format-numbers-using-javascript) – mortb Apr 17 '18 at 12:06
  • the question's most popular answer is using a library, which isn't the best solution. secondly, you will find the problem at hand is including commas "during countup" and not when the countup function is completed. – Zach Smith Apr 17 '18 at 12:29

1 Answers1

0

You can use regex:

nStr.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

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


        $({countNum: $this.text()}).animate({
                countNum: countTo
            },
            {
                duration: 999,
                easing:'linear',
                step: function() {
                    $this.text(addCommas(Math.floor(this.countNum)));
                },
                complete: function() {
                    $this.text(addCommas(this.countNum));
                    console.log('finished')
                }
            });

        function addCommas(nStr){
            return nStr.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="number counter" data-count="300000">300,000</span>
KL_
  • 1,503
  • 1
  • 8
  • 13