格式化金钱,通过乘以小时*计算(db中的多个条目)

时间:2016-03-27 12:13:45

标签: php mysql rate

我在这里面临一个难题,而且我不知道如何解决它。 我有2张不同的桌子。任务表和项目表。任务表包含花费的时间(以秒为单位),特定任务的每小时速率以及该条目属于哪个项目。所以基本上是这样的:

{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....

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

我正在选择' db中针对数组中特定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 $12 p/h and 2 task with $10 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 ,但最后一个函数返回 2,426.92 代替。

两种情况下的秒数和速率都是正确的。我不明白为什么与最终价值存在差异? 我猜我在项目下的任务越多,差异越大?现在我正在测试1-50个任务...每个项目

1 个答案:

答案 0 :(得分:1)

示例数据:

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。

在你的计算中可能会发生类似的事情。