For example, given the decimal value 5.66, representing 5 hours and 39 minutes, how would I round this number to 5 hours and 45 minutes (the nearest 15 minute interval), aka 5.75.
Similarly, if I had 5 hours and 36 minutes, or 5.6, this is closer to 5:30 than 5:45, so I’d want to get 5.5 out of it.
Trying to write this in PHP.
function round_decimal_time($time, $interval=15){
// Split up decimal time
$hours = (int) $time;
$minutes = $time - $hours;
// Convert base 10 minutes to base 60 minutes
$b60_m = $minutes * 60;
// Round base 60 minutes to nearest interval... (15 minutes by default)
// DONT KNOW HOW TO DO THIS PART
// If greater than or equal to 60, go up an hour
if($b60_m >= 60){
$hours += 1;
$minutes = 0;
} else {
// Otherwise, convert b60 minutes back into b10
$time = $hours + ($b60_m / 60);
}
return $time;
}
And again, some examples of what I’m trying to do.
Input: 5.66 (5:39 duration)
Output: 5.75
Input: 5.6 (5:36 duration)
Output: 5.50
Input: 5.05 (5:03 duration)
Output: 5.00
Rounding to
'nearest number $X'is done by:So, after (0.66 * 60 = 39.6):
You can use
ceilandfloorin a similar manner if you always want to round down or up.Your total function would be: