Jump to content

[SOLVED] Floating Point Comparison


ainoy31

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/136582-solved-floating-point-comparison/
Share on other sites

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

}

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.