douzhicong5965 2016-11-15 03:25
浏览 20
已采纳

PHP添加值列表并不完全正确

I get a list of values from my database and I add them to get the sum of all the rows. PHP is not doing the addition correctly and I can't figure out why. I am working money with what I am doing. The result should be zero, but PHP is calculating the result to be $ -1.78. What is wrong with the following:

public function testAddition()
{
  $data = ['23.21','-38.20','14.99','0.00'];
  $total = 0;
  foreach ($data as $value) {
    $total += round(floatval($value), 2);
    var_dump($value);  // value to add
    var_dump($total);  // new total
  }
  // PHPunit results a success to zero, this is wrong, $total = -1.776...
  $this->assertEquals(0, $total); 
}

Outputs the following:

string(5) "23.21"  // value to add
float(23.21)  // new total
string(6) "-38.20" // value to add
float(-14.99)  // new total
string(5) "14.99"  // value to add
float(-1.7763568394003E-15)  // <-- this is wrong, should be zero
string(4) "0.00"  // value to add
float(-1.7763568394003E-15)  // new total
  • 写回答

1条回答 默认 最新

  • dongqufi82315 2016-11-15 03:35
    关注

    The result is -1.7763568394003E-15 or 0.0000000000000017763568394003; which, when "rounded" = 0.00. This is just a problem calculating numbers as "floats" - there will nearly always be small remainders somewhere

    The solution is to round the result as well? Or multiple by 100 and use (int) and then divide by 100 again (although the divide theoretically could leave a remainder)

    Also, while it doesn't answer your question, you don't need the floatval, you can just use $total += round($value, 2); as PHP does it's own casting for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大