Page 1 of 1

Subtraction weirdness

Posted: Wed Dec 14, 2011 11:32 am
by ulbador
I know this is due to floating point math fun, but I'm curious why we have never run into this before.

Code: Select all

<?

$total = 27+2.89+7.99;

$amounts[] = 27;
$amounts[] = 2.89;
$amounts[] = 7.99;


foreach ($amounts as $key => $value) {
   $total -= $value;
    echo "$total $value\n";
}

?>
Expected:
10.88 27
7.99 2.89
0 7.99

Actual:
10.88 27
7.99 2.89
1.776356839E-15 7.99


My company has been running PHP since the /FI days, and I'm certain we've had similar code to this. I've never seen this result before. I've tried a few different combinations, and this one seems 100% repeatable on our system, while similar code returns the "correct" response.

This honestly scares me a bit as I know in our large codebase there are probably similar cases. What is it about this specific code that triggers this behavior so I can track down similar places?

Thanks!

Re: Subtraction weirdness

Posted: Wed Dec 14, 2011 1:07 pm
by tr0gd0rr
If your numbers are strings and you cast to string at each step, php won't have floating point errors. The following produces the expected output.

Code: Select all

$total = (string) (27+2.89+7.99);
$amounts[] = '27';
$amounts[] = '2.89';
$amounts[] = '7.99';

foreach ($amounts as $key => $value) {
   $total -= $value;
   $total = (string) $total;
   echo "$total $value\n";
}