How to increment number using animate with comma u

2020-02-05 03:58发布

I'm trying to increment a number inside an element on page. But I need the number to include a comma for the thousandth place value. (e.g. 45,000 not 45000)

<script>
// Animate the element's value from x to y:
  $({someValue: 40000}).animate({someValue: 45000}, {
      duration: 3000,
      easing:'swing', // can be anything
      step: function() { // called on every step
          // Update the element's text with rounded-up value:
          $('#el').text(Math.round(this.someValue));
      }
  });
</script>
<div id="el"></div>

How can I increment a number using animate with comma?

2条回答
姐就是有狂的资本
2楼-- · 2020-02-05 04:25

You should also add a complete function as such:

step:function(){
    //..
},
complete:function(){
    $el.text(commaSeparateNumber(Math.round(this.someValue)));
}

Updated Fiddle: Demo

查看更多
小情绪 Triste *
3楼-- · 2020-02-05 04:40

Working Demo http://jsfiddle.net/4v2wK/

Feel free to change it more for your need, you can also look at the currency formatter, Hope this will fit your need :)

Code

// Animate the element's value from x to y:
  var $el = $("#el"); //[make sure this is a unique variable name]
  $({someValue: 40000}).animate({someValue: 45000}, {
      duration: 3000,
      easing:'swing', // can be anything
      step: function() { // called on every step
          // Update the element's text with rounded-up value:
          $el.text(commaSeparateNumber(Math.round(this.someValue)));
      }
  });

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

**output* enter image description here

查看更多
登录 后发表回答