Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Math.floor not working as expected

Tags:

javascript

function TimeConvert(num) {
    for (i = 0; i < num; i+= 60) {
        if (num % 60 < 60) {
            var hours = Math.floor(i / 60);
            if (hours == 0) {
                var minutes = num % 60;
            } else {
                minutes = num % (60 * hours);
            }
        }
    }
    return hours + ":" + minutes;
}

When I call TimeConvert(60), it returns 0:0 instead of 1:0... why? Do I have to add a conditional to check whether num % 60 == 0 in such cases?

like image 801
bard Avatar asked Jun 08 '26 11:06

bard


2 Answers

Why would you need to iterate ?

function TimeConvert(num) {
    var hours   = Math.floor( num / 60 );
    var minutes = num % 60;
    //minutes = minutes < 10 ? '0'+minutes:minutes
    return hours + ":" + minutes;
}

FIDDLE

like image 138
adeneo Avatar answered Jun 10 '26 10:06

adeneo


The problem is with i < num it should be i <= num instead. Your for is only executed once with i=0, because on the very next step i gets +60 and i < num becomes false.

And, anyway, the whole function should just be:

function TimeConvert(num) {
    var hours = Math.floor(num / 60);
    var minutes = num % 60;
    return hours + ":" + minutes;
}
like image 30
mishik Avatar answered Jun 10 '26 10:06

mishik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!