1

I am a beginner with JS and have no idea how to pull it off here. Idea is to have commas in the numbers to make it easier to read while counting up and also the final static result should have commas.

Eg: "10,000"

var a = 0;
$(window).scroll(function() {

  var oTop = $('#counter').offset().top - window.innerHeight;
  if (a == 0 && $(window).scrollTop() > oTop) {
    $('.counter-value').each(function() {
      var $this = $(this),
        countTo = $this.attr('data-count');
      $({
        countNum: $this.text()
      }).animate({
          countNum: countTo
        },

        {

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

        });
    });
    a = 1;
  }

});

1 Answers1

3

Best way is to use the built-in Intl object. More info here.

const number = 123456;
const formattedNumber = new Intl.NumberFormat('en-us').format(number);

console.log({ formattedNumber }); // 123,456
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
P.E. Joëssel
  • 1,393
  • 10
  • 18
  • @AdarshBhadauria ... you're dealing with jQuery specific JS code. The dollar function wrapping of values happens every time you want or have to deal with a jQuery specific object which is one possible entry into the jQuery domain specific language. Such objects offer tons of handy tools/processes in order to bend (mostly UI specific) JS behavior to your will. In your case you just need to copy the above answer's code snippet into your only method which actually does an UI display ... `complete: function() { $this.text(new Intl.NumberFormat('en-us').format(this.countNum)); }` – Peter Seliger Feb 24 '21 at 08:51