Rounding off numbers

Hi all,

Here is my piece of code.

1
2
3
4
5
6
7
8
9
10
11
double availableUnits       = calculateAvailableUnits(some arguments);
int    minimumRequiredUnits = getMinimumRequiredUnits(some arguments);

std::cout<<"minimumRequiredUnits = "<<minimumRequiredUnits<<std::endl; //prints 30
std::cout<<"availableUnits = "<<availableUnits<<std::endl; //prints 30

if (availableUnits < minimumRequiredUnits)
{
    //throw exception;
}
//rest of the code 


Even though both have the value 30 in it, the if-condition gets satisfied and exception is thrown which is wrong. I studied the problem a little more and found that the double variable availableUnits infact doesn't contain 30, instead it contains 29.9999. Is there anyway I can get rid of this problem?

calculateAvailableUnits function does some calculation which involves fractions, so the result 29.9999 instead of 30.
Last edited on
The only way without changing calculateAvailableUnits() is to relax the requirement. a<b-epsilon, where epsilon is some appropriately small value.
Last edited on
Topic archived. No new replies allowed.