Skip to content

Instantly share code, notes, and snippets.

@Simcamb
Last active May 5, 2018 21:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Simcamb/5850438 to your computer and use it in GitHub Desktop.
Save Simcamb/5850438 to your computer and use it in GitHub Desktop.
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