Jump to content


Photo

Weird result when subtracting


  • Please log in to reply
1 reply to this topic

#1 tfoster

tfoster
  • Members
  • PipPip
  • Member
  • 10 posts

Posted 03 July 2006 - 04:15 PM

Just wanted to see if anyone has ever run across this before.

$balance = $row[totalcost];

Then I am selecting checks from another table, and while fetching them, subtracting them from the balance, so:

while($rowCheck = mysql_fetch_array($resultCheck))
  $balance = $balance - $rowCheck[checks_amount];

I get down to the last check, everything is running smoothly.  The balance is 107.56 and the last check is 107.56.  When I subtract the two, I am getting 3.98457E-13.  What is the deal?

I have found that I can get around this by adding the total of the checks and then subtracting them from the balance.  I was just curious if anyone know why this is happening.  It is not as if checks are being entered as 107.5600000000000045...

Thanks for any feedback!

#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 03 July 2006 - 05:18 PM

The result that you're seeing is the result of the fact that nice "normal" floating point decimal numbers can't be stored accurately as binary. What you can do is compare the result of the subtraction to a small decimal number such as 0.001 and if it is less than that, just assume the result is zero.

Ken




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users