C++ Help.... how can i Round X to n digits?

chiwawa626

Lifer
Aug 15, 2000
12,013
0
0
C++ Help.... Round X to n digits (after the decimal point)
so like
x= 1234.12345
n=2
answer would be 1234.12

how can i do that?!??!?!
 

Platypus

Lifer
Apr 26, 2001
31,046
321
136
You want to set your IOS flags.

cout<<setiosflags(ios::left) | setprecision(2)<<blah blah<<;

Something like that, I haven't used that in a while, so the syntax may be a bit off.
Make sure "X" is a double.
 

flood

Diamond Member
Oct 17, 1999
4,213
0
76
can anyone see why this wouldnt work?
((double)((long)(x*(10^n))))/(10^n)
 

arcain

Senior member
Oct 9, 1999
932
0
0
how about:

variable = (double)((long)(variable + 0.5));

durr.. missed the 2 decimals part..

or in this case..

multiply variable by 100 and then divide by 100 afterwards..
 

BigFatCow

Diamond Member
Aug 11, 2001
3,373
1
0


<< can anyone see why this wouldnt work?
((double)((long)(x*(10^n))))/(10^n)
>>



you cant do 10^n, it would have to be pow(10,n)

make sure to include math.h

((double)((long)(x*(pow(10,x)))))/(pow(10,x));

that should work
 

Platypus

Lifer
Apr 26, 2001
31,046
321
136
yes, i forgot the ::fixed and the floatpoint.
It's been a few years since I needed that.

I am glad it worked for ya :)

Edit: make sure to #include the iomanip.h library...


 

flood

Diamond Member
Oct 17, 1999
4,213
0
76


<<

<< can anyone see why this wouldnt work?
((double)((long)(x*(10^n))))/(10^n)
>>



you cant do 10^n, it would have to be pow(10,n)

make sure to include math.h

((double)((long)(x*(pow(10,x)))))/(pow(10,x));

that should work
>>



well, of course :p
((double)((long)(x*(pow(10,x)))))/(pow(10,x));
doesnt work properly all the tine tho
 

hans007

Lifer
Feb 1, 2000
20,212
18
81
the setios stuff would just make it print differently. the value would still be the same. to round it you'd probably wanna go do this..



say n is 2.


then multiply it by 10^2.


use a truncation function, or cast it , x=(long) (number * pow(10,n)) to truncate the decimals;

then take the number, cast it back into a double and divide by number= (double) /pow (10,n)