ainoy31 Posted December 11, 2008 Share Posted December 11, 2008 Hello- I am having an issue with comparing floating point values. I did a var_dump() on both of my variables and one of them is a string and the other is a float. So, I did a type cast of the string variable to a float. Here is my code: $balance = (float)$data->balance; $foundMoney = 0; $current = 0; while(($row = fncDBMoveNext($result)) != NULL) { if($balance > $foundMoney) { if($row->amount > ($balance - $foundMoney) ) { $agingAmount = $balance - $foundMoney; $foundMoney += ($balance - $foundMoney); } else { $foundMoney += $row->amount; $agingAmount = $row->amount; } if ($row->age > $age) { $age = $row->age; } } else { break; } } If I var_dump the $balance and $foundMoney variables, it returns a float(xxx.xx). Here is the issue. During the loop, the $foundMoney value will become equal to or greater than the value of the $balance, thus cause it to break out of the if($balance > $foundMoney) comparison. However, when $foundMoney is float(250.35) and $balance is float(250.35) it does not cause it to break out but rather continue the unwanted calculation. Hope this is easy to read and understand. Much appreciation. Quote Link to comment https://forums.phpfreaks.com/topic/136582-solved-floating-point-comparison/ Share on other sites More sharing options...
PFMaBiSmAd Posted December 11, 2008 Share Posted December 11, 2008 Read the warning at this link - http://us.php.net/float Quote Link to comment https://forums.phpfreaks.com/topic/136582-solved-floating-point-comparison/#findComment-713050 Share on other sites More sharing options...
ainoy31 Posted December 11, 2008 Author Share Posted December 11, 2008 Thanks man. I saw this page and overlooked the warning section. I used the bccomp() function and it helped me out. Here is what I used: $value = bccomp($balance, $foundMoney, 2); Instead of using if($balance > $foundMoney), I plugged in this: if($value == 1) { .....etc } Quote Link to comment https://forums.phpfreaks.com/topic/136582-solved-floating-point-comparison/#findComment-713057 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.