Convert Float to Time in JavaScript (Hours and Minutes)
How to Convert a given float number to hours and minutes. What is the JavaScript function we should use to convert float to time in JavaScript? Here, we share the easiest solution to convert a given number to time (hours and minutes).
In this tutorial, you will see how to convert float numbers to time (hours and minutes) in JavaScript. There are a number of ways to convert float to time. However, we use the Math.floor() and Math.round() function from the Javascript Math object.
Convert Float to Time (Hours and Minutes)
The following javascript snippet converts a given float to hours and minutes.
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) + '';
// Add padding if need
if (minute.length < 2) {
minute = '0' + minute;
}
// Add Sign in final result
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
Demo
See the Pen
Convert Float to Hours and Minutes by SpeedySense Editorial (@speedysense)
on CodePen.
Convert a number to hours and minutes
The following javascript snippet converts a given float 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));
Output
1:28
5:50
20:36
Demo
See the Pen
Convert Number to Hours and Minutes by SpeedySense Editorial (@speedysense)
on CodePen.
We hope you have found this article helpful. Let us know your questions or feedback if any through the comment section in below. You can subscribe our newsletter and get notified when we publish new WordPress articles for free. Moreover, you can explore here other JavaScript related articles.
If you like our article, please consider buying a coffee for us.
Thanks for your support!
Buy me a coffee!
Join the Discussion.