Error in rounding off long double

So, i wrote this code to round off long double. But its showing some error beyond me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
long double round(long double a,int i)
{
long double temp=0;
long long ii=0;
ii=pow(10,i);

temp=a*ii;
cout<<fixed<<setprecision(20)<<temp<<endl;
temp+=0.5;
cout<<temp<<endl;
temp=floor(temp);
cout<<temp<<endl;
temp=temp/ii;
cout<<temp<<endl;

return(temp);
}



203214164615.76216505467891693115
203214164616.26216505467891693115
203214164616.00000000000000000000
20.32141598719999999942



Any help!?
Why diving by long long giving approximation? HOw to fix this?
What values do you pass to round?
1
2
3
long double a=0,b=0;
a=20.32141646157621672176152;
cout<<fixed<<setprecision(20)<<"Round of "<<a<<" is "<<round(a,10)<<endl;


Also I tried
 
temp*=pow(10,-i)

It gives

203214164615.76216505467891693115
203214164616.26216505467891693115
203214164616.00000000000000000000000000000000000000000000000000
20.32141646160001127903449447131833949242718517780304
Round of 20.32141646157621650559 is 20.32141646160001127903
Last edited on
Ah, ok, so you want to round to a certain decimal place. It's not really a good idea to do that because many floating point values can't be stored exactly so you will get rounding errors. If you just want to show a certain number of decimals it's much better to use setprecision when printing the value.
Thank you for your reply.

As this is my assignment, i must have to do so!
I understand precision is only helpful in displaying the variable. But while doing operation on it it is using its actual value.

Any other way to do so?
Topic archived. No new replies allowed.