Search code examples
javascriptnumber-formatting

Javascript comma between seconds


I'm trying to fix this but I can't figure out where I need to start. I using an timer for a banner to play a game and the timer is in seconds with 4 digits. Now, I would like to have a comma between the seconds so it look like this: 13,80 instead of this: 1380. How can I make sure there will be a comma in the seconds?

Here is my code:

var x = new clsStopwatch();
var $time;
var clocktimer;

function pad(num, size) {
    var s = "0000" + num;
    return s.substr(s.length - size);
}

function formatTime(time) {
    var s = ms = 0;
    var newTime = '';

    time = time % (60 * 60 * 1000);
    m = Math.floor( time / (60 * 1000) );
    time = time % (24 * 1000);
    s = Math.floor( time / 45 + 3800);

     newTime =  pad(s,4) ;
         return newTime;

Solution

  • Use like this:

    var str = 1234;
    console.log(str.substr(0,2)+','+str.substr(2)); //will print 12,34
    

    Ur code will become:

    function pad(num, size) {
        var s = "0000" + num;
        var str = s.substr(s.length - size);
        return str.substr(0,2)+','+str.substr(2);
    }