anson920520 anson920520 - 7 months ago 10
Javascript Question

Adding a comma to split numbers

I am creating a fancy number box. The below is a function that when people finishing loading there ll be a number box count up to the result:

function countUp(count){
var div_by = 100,
speed = Math.round(count/div_by),
$display = $('.count'),// i bind the function to the class count
run_count = 1,
int_speed = 24;

var int = setInterval(function() {
if(run_count < div_by){
$display.text(speed * run_count);
run_count++;
} else if(parseInt($display.text()) < count) {
var curr_count = parseInt($display.text()) + 1;
$display.text(curr_count);
} else {
clearInterval(int);
}
}, int_speed);
}
countUp(6435);


It's working fine by i'd like to add comma to split the thousand like 6,345
I tried to convert the result using
toString()
but it doesn't work

countUp(6435).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

Answer

you can use toLocaleString method

countUp(6435).toLocaleString();