0

the result of this should be zero!

echo array_sum([-61.50,50.00,10.50,1.00,0.00,50.00,-16.73,-20.00,-55.75,42.48]);

Why is giving -7.105427357601E-15?

3 Answers3

0

Because floating point values (which you have here when you use decimals) are not exact. They're approximations.

The error in that approximation comes out to -7.105427357601E-15 when summing these values.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84
0

It's because of floats. If you want to calculate something with precision 2 (for this example) you should use something like this:

$el = [-61.50,50.00,10.50,1.00,0.00,50.00,-16.73,-20.00,-55.75,42.48];
$sum = 0;
foreach ($el as $e) {
    $sum += $e * 100;
}

echo $sum / 100;

You should never trust to float values. Another example from Javascript (Google developer Console):

enter image description here

Artur R.
  • 248
  • 2
  • 9
0

Just try round(), you will get the same result.

echo round(array_sum([-61.50,50.00,10.50,1.00,0.00,50.00,-16.73,-20.00,-55.75,42.48]));
Googlian
  • 6,077
  • 3
  • 38
  • 44
  • but i need the floating points... round(array_sum([-61.50,50.00,10.50,1.00,0.00,50.00,-16.73,-20.00,-55.75,42.48]),2); works properly :) – Daniel Novo Mar 04 '19 at 12:53