3
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?

5
  • Did you try tracing the code with a debugger? Commented Jun 30, 2013 at 14:30
  • 2
    num % 60 < 60 is always satisfied if num is numeric and finite Commented Jun 30, 2013 at 14:32
  • Yes, it works when i call TimeConvert(126) for example, it returns 2:6. But when I call TimeConvert(120), it returns 1:0 and not 2:0. Commented Jun 30, 2013 at 14:32
  • trace with the value for which it misbehaves Commented Jun 30, 2013 at 14:33
  • 1
    Your condition is for less than your num; try making it <= Commented Jun 30, 2013 at 14:34

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

IIUC, OP doesn't want to format the minutes as a two-digit number
@JanDvorak - just remove that line then!
This worked perfectly, thanks! You're right, I've got to stop thinking in terms of iteration all the time.
3

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.