Skip to content

Instantly share code, notes, and snippets.

@Simcamb Simcamb/floatToHour.js
Last active May 5, 2018

Embed
What would you like to do?
Converts a float (like 1.5) to an hour (1h30)
/**
* Will convert any float (pos or neg) to an hour value
* floatToHour(1.5) will return "1h30"
*
* @param {number}
* @returns {string}
*/
function floatToHour(num) {
var sign = num >= 0 ? 1 : -1;
// Get positive value of num
num *= sign;
// Separate the int from the decimal part
var intPart = Math.floor(num);
var decPart = num - intPart;
var minutes = Math.floor(decPart * 60);
// Sign result
sign = sign == 1 ? '' : '-';
// pad() adds a leading zero if needed
return sign + intPart + 'h' + pad(minutes, 2);
}
/**
* Will add leading zeroes to any number to output a string with desired length
* pad(25, 3) will return "025"
*
* @param number
* @param length
* @returns {string}
*/
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.