Skip to main content

JavaScript function to converts a float (like 1.5) to an hour (1h30).

//Converts a float (like 1.5) to an hour (1h30)
// https://gist.github.com/Simcamb/5850438
function floatToHour(num) {
  var sign = num >= 0 ? 1 : -1;
  var min = 1 / 60;

  // Get positive value of num
  num = num * sign;

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

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

  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);
  return sign + intpart + 'h' + minutes;
}

// Example
console.log( floatToHour(1.5) ); // 1h30