"Ivan Vecerina" <IN*****************@ivan.vecerina.comwrote in message

news:88**************************@news.hispeed.ch. ..

"Gary Wessle" <ph****@yahoo.comwrote in message

news:87************@yahoo.com...

: I googled, RTM, checked round, floor, ceil, setprecision for no avail.

: I have a vector<doublewhich I need to round its elements to the nth

: digit so that if n is 2 then

: 1.135 would be 1.14

: 0.9955 would be 1.00

For example:

double mul = pow(10,n);

for( ... i = .... )

v[i] = floor( v[i]*mul + 0.5 ) / mul;

There's no guarantee that that will result in the value desired. Remember,

floating-point values are binary representations, and can only be exactly

represented for a small subset of specific values. Just like there's no way

to represent 1/3 exactly using decimals (it's .3333333... forever), there is

no way to represent many fractions using binary. So making this type of

calculation, where n can be anything, may result in values near to what you

want, but not exact.

The question is, where does the rounding need to occur? If it's just for

output, then the correct thing to do would probably be to format the output,

not to modify the stored value.

If you're talking about currency (such as dollars and cents) or some other

fixed-point system, then you might want to simply scale everything upwards

as needed. For example, instead of storing 1.135 as 1.14, you could scale

it up to 113.5, then round that to the integer 114. Then you can stick the

decimal where you want it when displaying or printing out the value.

If you've got a more complex (or generic) situation, then perhaps you could

explain it more fully and someone could suggest a solution for your

particular needs.

-Howard