我从数据库中获得一个值列表,并将它们相加以获得所有行的总和。PHP没有做正确的添加,我不知道为什么。我正在用我所做的工作赚钱。结果应该是0,但是PHP计算的结果是$ -1.78。
有什么问题?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);
}
输出如下内容:
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.7763568394003E-15或0.0000000000000017763568394003;当"四舍五入"= 0.00时。这只是一个将数字计算为"浮点数"的问题-几乎总是在某处有小的余数
解决方案是四舍五入的结果?或者乘以100,然后使用(int),然后再除以100(尽管理论上除法可以留下余数)
另外,虽然它不回答你的问题,你不需要floatval,你可以只使用$total += round($value, 2);
作为PHP做它自己的铸造为您。