例如,给定表示5小时39分钟的十进制值5.66,我如何将该数字四舍五入到5小时45分钟(最接近的15分钟间隔),即5.75。
同样,如果我有5小时36分钟,或者5.6,这比5:45更接近5:30,所以我想从中得到5.5
尝试用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;
}
再说一遍,我想做的一些例子。
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
四舍五入到'nearest number $X'
由完成
round($number/$X)*$X;
因此,在(0.66*60=39.6)之后:
round(39.6/15)*15=45
如果您总是想向下或向上取整,则可以以类似的方式使用ceil
和floor
。
你的总功能是:
round_decimal_time($time,$round=15){
return (round($time * 60 / $round) * $round) / 60;
}
$a = 5.66;
var_dump(round($a / 0.25) * 0.25);
这种方法适用于任何舍入。
例如:如果你有7,想四舍五入到最接近的数字,除以5(5、10、15、20等),你可以这样做:
round(7 / 5) * 5
若要将任何内容四舍五入到最接近的x
,请除以x
,四舍五五入到最近的整数,然后乘以x
。