user1419810
user1419810

Reputation: 846

Format number with thousands seperator and 2 decimal places

I'm currently populating a div with jquery but need to format the output with a thousands separator and to two decimal places whilst also keeping the output as a number.

FYI I'm currently populating the div using:

var prev_count = 120;
var new_count = 20.50;

    var count_till = prev_count < new_count ? new_count : new_count - 1;
    jQuery({ Counter: prev_count }).animate({ Counter: count_till }, {
        duration: 600,
        easing: 'swing',
        step: function () {
            jQuery("#count_div").text(Math.ceil(this.Counter));
        }
    });

Starting variable is 120 and this is meant to count down to 20.50 however it ends on 20, not 20.50, is this possible if so how would i go about it?

Here is my jsfiddle

Upvotes: 3

Views: 1253

Answers (2)

zerohero
zerohero

Reputation: 583

Math.Ceil returns the smallest integer greater than or equal to a given number. Integers do not have fractions (which is what you are looking for)

You would need to replace your line where you output the number to this:

jQuery("#count_div").html(this.Counter.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'));

Here is a working JSFiddle: https://jsfiddle.net/12g2pj4L/2/

Upvotes: 1

user1419810
user1419810

Reputation: 846

Ok, so I managed to solve this myself using a function to add in the thousands separator and also toFixed(2) to set the decimal places, code as below:

$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}

var prev_count = "1125";
prev_count = prev_count.split(',').join('');
prev_count = parseInt(prev_count);

var new_count = 1320.50;

var count_till = prev_count < new_count ? new_count : new_count;
jQuery({ Counter: prev_count }).animate({ Counter: count_till }, {
    duration: 7000,
    easing: 'swing',
    step: function () {
    jQuery("#count_div").html(this.Counter.toFixed(2)).digits();

    }
});

and fiddle here

Upvotes: 0

Related Questions