格式化金钱,通过乘以小时数 * 费率计算(数据库中的多个条目)

Format money, calculated by multiplying hours * rate (multiple entries in db)

我遇到了一个难题,不知道怎么解决。 我有 2 个不同的 table。 A 任务 table 和项目 table。任务 table 包含花费的时间(以秒为单位)、该特定任务的每小时费率以及该条目属于哪个项目。所以基本上是这样的:

{id} - {seconds} - {rate} - {projectId}

现在,我正在计算这样一个特定任务的每小时计费率:

function calc ($Totalseconds, $rate){
  $minutes = $Totalseconds/60;      //minutes
  $money = $rate * ($minutes / 60); //hours
  return $money;
}
...
$money = calc($task['seconds'], $task['rate']);
$value = number_format($money,2); //ex. 1,824.69

这当然行得通....例如:

task1 is 1,824.69
task2 is 24.33
etc....

只要一个项目只有几个任务,那么该项目的总计费率就是正确的。但是当一个项目下有多个任务时,总价值与我用计算器手动添加它们时有点不同......所以在另一页中我显示了特定项目的总计费率通过计算该特定项目的所有任务和费率。

我是 'selecting' 数据库中针对数组中特定 projectId 的所有任务,然后执行:

//array projArray has the sum of all seconds and rate for every task under a specific project
//for example a project has 10 tasks with rate  p/h and 2 task with  p/h
//so projArray has 2 arrays. One for the total time in seconds for the 10 tasks + their rate and one for the 2 tasks + their rate.
$total = 0;
foreach($projArray as $value) {
  $total += calc($value['TotalTime'], $value['rate']); 
}
$Totalvalue = number_format($total,2);

这就是问题所在...当我手动添加所有任务的计费率时,针对特定项目,使用计算器我得到 2,426.91 但最后一个函数 returns 2,426.92 代替。

两种情况下的秒数和速率都是正确的。我不明白为什么最终值会有所不同? 我想我在一个项目下的任务越多,差异就越大?现在我正在测试 1-50 个任务……每个项目

示例数据:

a: 1,233
b: 1,233
c: 1,233

number_format((a + b + c), 2) = 3,70
number_format(a, 2) + number_format(b, 2) + number_format(c, 2) = 3,69

当您对每个任务单独调用 number_format 时,将四舍五入 0,003。

您的计算中可能发生了类似的情况。