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.

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

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序