why isn't this rounding properly?

see comments in code. u can see when 55.5000 is calculated, it rounds to 55.
Then i assign the value manually to 55.5000, and it rounds properly to 56.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int roundInt(double d1);
void main(){
	cout.setf(ios::fixed);
	cout.setf(ios::showpoint);
	cout.precision(4);

	double d1 = 42.555;
	int dollars1 = static_cast<int>(floor(fabs (d1)));
	cout<<"doll: "<<dollars1<<endl; //prints 42 
	double leftOver = (fabs (d1) - dollars1)*100;
	cout<<"leftOver: "<<leftOver<<endl; //55.5000
	int cents2 = roundInt(leftOver); 
	cout<<"cents2: "<<cents2<<endl; //55 rounds incorrectly 
	leftOver = 55.500;
	int cents3 = roundInt(leftOver);
	cout<<"cents3: "<<cents3<<endl; //56 rounds correctly
}
int roundInt(double d1){
	int x=static_cast<int>(floor(d1+.5));
	return x;
}
u can see when 55.5000 is calculated
There is no 55.5000 calculated in code.
It just seems that way because you so not have enough precision. change line 5 to have 16 digit precision and see for yourself.
thanks. you're right, i get a leftover of leftOver: 55.4999999999999720.
this leads to my follow up:
why is (42.555 - 42.0000000000000000)*100 equal to the above?
ok, read some of it. From what I can understand numbers like .1 can't be represented in exact values in binary, unlike base 10. So what's the solution? Is there a rule of thumb for avoiding this kind of error. How should I fix the code to avoid this error.
Topic archived. No new replies allowed.