首页 > 解决方案 > PHP 中的舍入时间小数点后

问题描述

$time_taken = 286;

$time_taken = $time_taken / 60;  //Converting to minutes

echo $time_taken;

结果:4.7666666666667

但我需要:(期望:)

结果:5.17(预期)

我试过:round($time_taken,2);

但后来它给出了结果:

结果:4.77

标签: phptimerounding

解决方案


你读错了结果。但别担心。与时间打交道曾经让大多数开发者发疯。这就像一个通过仪式。

你得到了4.76 minutes,这是一样的4 minutes and 76 seconds

4 full minutes and 0.76 of a minute

分解它:

  • 4 minutes = 240 sec
  • 286 - 240 = 46

所以结果应该是 4 分 46 秒。

要计算它,您可以这样做:

$total = 286;

// Floor the minutes so we only get full minutes
$mins  = floor($total / 60);

// Calculate how many secs are left
$secs  = $total % 60; // Thanks @RiggsFolly for the tip

echo "$mins minutes and $secs seconds";

这是一个演示


推荐阅读