【问题标题】:Given a decimal time value, how could I round that to an interval?给定一个十进制时间值,我怎么能把它四舍五入到一个间隔?
【发布时间】:2012-01-26 21:45:42
【问题描述】:

例如,给定十进制值 5.66,表示 5 小时 39 分钟,我如何将这个数字四舍五入为 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

【问题讨论】:

    标签: php time decimal


    【解决方案1】:

    四舍五入到'nearest number $X' 由以下人员完成:

     round($number/$X)*$X;
    

    所以,在 (0.66 * 60 = 39.6) 之后:

     round(39.6/15)*15=45
    

    如果您总是想向下或向上取整,可以以类似的方式使用ceilfloor

    你的总功能是:

     round_decimal_time($time,$round=15){
         return (round($time * 60 / $round) * $round) / 60;
     }
    

    【讨论】:

    • 当 $round > 60 b.t.w. 时函数不正确,我会在一分钟内发布一个新的...
    【解决方案2】:
    $a = 5.66;
    var_dump(round($a / 0.25) * 0.25);
    

    这种方法适用于任何舍入。

    例如:如果您有 7 并且想要四舍五入到除以 5 的最接近的数字(5、10、15、20 等),您可以这样做:

    round(7 / 5) * 5
    

    【讨论】:

      【解决方案3】:

      要四舍五入到最接近的x,除以x,四舍五入到最接近的整数,然后乘以x

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多