0

I have a function written in PHP that calculates account balances by subtracting all payments from all charges.

Unfortunately I have one account that is returning a value of -4.5474735088646E-13 when I subtract 2716 from 2716. I was kind of expecting a 0.

I calculate the value in my function like so

$accountbalance = (float)$totalcharges - (float)$totalpayments;
return $accountbalance;

The secondary issue is that when I format the account balance with two decimal places I end up with -0.00

number_format($accountbalance,2)

weird, or what? What is causing this and how do I prevent it?

Vincent
  • 1,741
  • 23
  • 35
  • That's how floating point numbers work. – duffymo Jul 16 '14 at 18:45
  • your -4.54... number is just a really really tiny number, almost zero. Floating point imprecision for you. – Lochemage Jul 16 '14 at 18:46
  • Use `abs` to always have result as positive number – hindmost Jul 16 '14 at 18:47
  • I actually need to see negative numbers in this case so abs won't work for me, but I believe one of you had recommended rounding (before editing your comment) and that seems to do the trick. Also, sorry for posting a duplicate question. Didn't realize. – Vincent Jul 16 '14 at 18:53

0 Answers0