Search code examples
javascriptjquerynumber-formattingcsvdecimal-point

Adding commas, decimal to number output javascript


I'm using the following code to count up from a starting number. What I need is to insert commas in the appropriate places (thousands) and put a decimal point in front of the last two digits.

function createCounter(elementId,start,end,totalTime,callback)
{
    var jTarget=jQuery("#"+elementId);
    var interval=totalTime/(end-start);
    var intervalId;
    var current=start;
    var f=function(){
        jTarget.text(current);
        if(current==end)
        {
            clearInterval(intervalId);
            if(callback)
            {
                callback();
            }
        }
        ++current;
    }
    intervalId=setInterval(f,interval);
    f();
}
jQuery(document).ready(function(){
    createCounter("counter",12714086+'',9999999999,10000000000000,function(){
        alert("finished")
    })
})

Executed here: http://jsfiddle.net/blackessej/TT8BH/3/


Solution

  • Check out this page for explanations on slice(), split(), and substring(), as well as other String Object functions.

    var num = 3874923.12 + ''; //converts to a string
    numArray = num.split('.'); //numArray[0] = 3874923 | numArray[1] = 12;
    
    commaNumber = '';
    i = numArray[0].length;
    do
    {
        //we don't want to start slicing from a negative number. The following line sets sliceStart to 0 if i < 0. Otherwise, sliceStart = i
        sliceStart = (i-3 >= 0) ? i-3 : 0;
    
        //we're slicing from the right side of numArray[0] because i = the length of the numArray[0] string.
        var setOf3 = numArray[0].slice(sliceStart, i);
    
        commaNumber = setOf3 + ',' + commaNumber; //prepend the new setOf3 in front, along with that comma you want
    
        i -= 3; //decrement i by 3 so that the next iteration of the loop slices the next set of 3 numbers
    }
    while(i >= 0)
    
    //result at this point: 3,874,923,
    
    //remove the trailing comma
    commaNumber = commaNumber.substring(0,commaNumber.length-1);
    
    //add the decimal to the end
    commaNumber += '.' + numArray[1];
    
    //voila!