Jump to content

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

}

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.