Subtraction weirdness

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ulbador
Forum Newbie
Posts: 1
Joined: Wed Dec 14, 2011 11:25 am

Subtraction weirdness

Post 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!
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: Subtraction weirdness

Post 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";
}
Post Reply