I have an animated jquery counter that’s working fine, but I want to change the end number to a decimal number. So at the moment it’s counting up to 54000, but I want it to give me 54,000. How do I do this?
jsfiddle is here
jQuery(document).ready(function ($) {
$(".animated_stats").each(function () {
_this = $(this);
_this.find('.counter').each(function () {
var $this = $(this),
countTo = $this.attr('data-count');
$({ countNum: $this.text() }).animate({
countNum: countTo
},
{
duration: 2000,
easing: 'linear',
step: function () {
$this.text(Math.floor(this.countNum));
},
complete: function () {
$this.text(this.countNum);
}
});
});
});
});h1 {
color: black;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="animated_stats"> <h1 class="counter" data-count="54000"></h1> </div>
Advertisement
Answer
Try to use Number.prototype.toLocaleString().
Replace $this.text(this.countNum); with $this.text(this.countNum.toLocaleString());
jQuery(document).ready(function ($) {
$(".animated_stats").each(function () {
_this = $(this);
_this.find('.counter').each(function () {
var $this = $(this),
countTo = $this.attr('data-count');
$({ countNum: $this.text() }).animate({
countNum: countTo
}, {
duration: 2000,
easing: 'linear',
step: function () {
$this.text(Math.floor(this.countNum).toLocaleString());
},
complete: function () {
$this.text(this.countNum.toLocaleString());
}
});
});
});
});h1 {
color: black;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="animated_stats"> <h1 class="counter" data-count="54000"></h1> </div>