MOCKSTACKS
EN

# How to convert a float into time in Javascript?

``````function convertNumToTime(number) {
// Check sign of given number
var sign = (number >= 0) ? 1 : -1;

// Set positive value of number of sign negative
number = number * sign;

// Separate the int from the decimal part
var hour = Math.floor(number);
var decpart = number - hour;

var min = 1 / 60;
// Round to nearest minute
decpart = min * Math.round(decpart / min);

var minute = Math.floor(decpart * 60) + '';

if (minute.length < 2) {
minute = '0' + minute;
}

sign = sign == 1 ? '' : '-';

// Concate hours and minutes
time = sign + hour + ':' + minute;

return time;
}

console.log(convertNumToTime(11.15));
console.log(convertNumToTime(1.08));
console.log(convertNumToTime(-2.50));
console.log(convertNumToTime(2));
console.log(convertNumToTime(0.40));``````

### Output

11:09
1:05
-2:30
2:00
0:24

Convert a number to hours and minutes

``````function NumToTime(num) {
var hours = Math.floor(num / 60);
var minutes = num % 60;
if (minutes + ''.length < 2) {
minutes = '0' + minutes;
}
return hours + ":" + minutes;
}

console.log(NumToTime(88));
console.log(NumToTime(350));
console.log(NumToTime(1236));``````

1:28
5:50
20:36

## Conclusion

In this page (written and validated by ) you learned about . What's Next? If you are interested in completing Javascript tutorial, we encourage you simply to start here: Javascript Tutorial.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.