user3720435 user3720435 - 1 year ago 63
PHP Question

PHP adding a list of values does not total correctly

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

Answer Source

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.