Incorrect Calculation

So I’m writing some software and have come across something I haven’t before with regards to a calculation being made incorrectly. Initially I had noticed that one of my floats was actually a string instead, so I converted it to a float (outputs as “double”).

I still feel like it’s a typecasting issue (because if I just output this code alone it’s fine), but when I output the types they are indeed both floats (double) and integers where they should be.

[php]echo “
$amountIn=”.$amountIn." (type:".gettype($amountIn)."), $total=".$total." (type:".gettype($total).") and “;
$NEWamountIn = $amountIn100;
$NEWtotal = $total
100;
echo “$NEWamountIn=”.$NEWamountIn.” (type:".gettype($NEWamountIn)."), $NEWtotal=".$NEWtotal." (type:".gettype($NEWtotal).")
";

echo “Which emeans that (type:”.gettype($amountIn).") “.$amountIn.”*100 = “;
$amountIn = intval($NEWamountIn);// Convert to INT
echo $amountIn.” (type:".gettype($amountIn).") and that (type:".gettype($total).") “.$total.”*100 = “;
$total = intval($NEWtotal);// Convert to INT
echo $total.” (type:".gettype($total).").";
if($amountIn != $total) {
echo “WTF? How are they not equal?”;
}[/php]

And here’s what it outputs. (notice the 2nd line has an incorrect calculation)
[sup]$amountIn=220.21 (type:double), $total=220.21 (type:double) and $NEWamountIn=22021 (type:double), $NEWtotal=22021 (type:double)
Which emeans that (type:double) 220.21100 = 22020 (type:integer) and that (type:double) 220.21100 = 22021 (type:integer).WTF? How are they not equal?[/sup]

Am I losing my marbles?

Just a follow-up to show my current code:

[php]if ($invoiceID == “1233791201”) {
echo “
$amountIn = “.$amountIn.” (”.(float)$amountIn.") and $total = “.$total.” (".(float)$total.")
";
if((float)$amountIn !== (float)$total)
echo “WTF? How are they not equal?”;
else
echo “They are finally equal”;
}[/php]

And my current output:

[sup]$amountIn = 220.21 (220.21) and $total = 220.21 (220.21)
WTF? How are they not equal?[/sup]

I have no idea why 220.21 is not equal to 220.21

I ran into a similar situation with floats. The php.net site even states that comparing floats is usually problematic. If I remember right I converted them to strings and compared them that way since it was really the only way to keep their decimal places intact, converting to int would strip those off. You can read more on the issue http://php.net/manual/en/language.types.float.php

Seems to work as expected on 64bit system. You might need BC math functions.

Try using echo serialize($var); on the different vars and calculations to see what the number really is.

Sponsor our Newsletter | Privacy Policy | Terms of Service