0

I've come across some strange behavior while doing simple computations in PHP. Consider the following code:

$numbers = [29, -6.01];

$a = 22.99;
$b = array_sum($numbers);
$c = (float) array_sum($numbers);
$d = 22.99;

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($a - $b);
var_dump($a - $c);
var_dump($a - $d);

The expected output of the var_dump statements should be:

float(22.99)
float(22.99)
float(22.99)
float(22.99)
float(0)
float(0)
float(0)

Instead the output is:

float(22.99)
float(22.99)
float(22.99)
float(22.99)
float(-3.5527136788005E-15)
float(-3.5527136788005E-15)
float(0)

So the results of the array_sum function calls (while showing the correct value when dumped) are somehow different when the actual subtraction is executed.

I've tried this on PHP 7.0.25. I couldn't find any bug reports or any other resources describing this behavior. I'd like be sure I'm not missing anything here before submitting a bug report.

Bogdan
  • 43,166
  • 12
  • 128
  • 129
  • 1
    [Is floating point math broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Mark Baker Nov 22 '17 at 16:53
  • Exactly how precise do you need your math? 15 decimal places seems close enough for the sum that you're doing – Mark Baker Nov 22 '17 at 16:54

0 Answers0