Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP calculation is flawed

I am writing a small script to calculate tax values after deductions. My application has several PHP scripts that provide CRUD functionality. I can add monthly expenses, total billed earnings and then calculate how much corporation tax is owed.

All of the data is stored in a database, however I came across an interesting problem when doing the calculations, I'll simplify the code below, so that it can be reproduced:

$total = 1.0;
$tax = 0.2;
$expenses = 0.05;

echo (($total-$tax) + $expenses); // this echo's 0.85
// (1.0 - 0.2) + 0.05 

if( (($total-$tax) + $expenses) == 0.85 ) {
    echo "totals add up";
}
else {
    echo "accounting error";
}

The idea is that all of the totals are calculated as percentages. 1.0 being 100% of the earnings and the expenses for the month in question is 5% (not really, but for the sake of argument, as my real calculations are a little bit more convoluted), either way this seems to be the simplest that I can get my calculations down to.

So 100% (earnings) - 20% (corporation tax) + 5% (expenses claims) should leave me with a 85% of the total. As shown by the first echo statment.

The if statement however trips up and says "accounting error". What is happening here?

like image 432
Husman Avatar asked Mar 13 '13 12:03

Husman


2 Answers

take a look at the manual for comparing floating points: http://php.net/manual/en/language.types.float.php

like image 26
djjjuk Avatar answered Oct 23 '22 05:10

djjjuk


This is a common problem with floating point calculation. To put it short, some decimal number's can't be described exactly in binary.

The common solution is to stick with integers and calculate everything in cents and only when outputting divide by 100.

like image 125
akirk Avatar answered Oct 23 '22 06:10

akirk