Gary said:
Hi
I googled, RTM, checked round, floor, ceil, setprecision for no avail.
I have a vector<double> which 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
thanks
This is a right royal pain in the wossname. It seems that everybody
gets so carried away with significant figures and thinks there is no
good reason to use number of decimal places.
For your use in currencies though using reals is a very bad idea. You
should be using an integer type multiplied by some value (100 or 1000)
depending on the currency and the accuracy required.
Having said that though if you have old code that's already using
floats to store money I just hope it's for reporting purposes...
Here is what I came up with (f is a real, set dp to the number of
places):
int mag = int( std::log10( f ) );
if ( dp + mag < 1 )
ss << std::setprecision( dp + 1 ) << 0.0;
else
ss << std::setprecision( dp + mag + 1 ) << f;
I'm sure this has all sorts of interesting behaviour for extreme values
and numbers of places. I'm also not sure what happens if dp is set to a
negative value - haven't needed it and haven't thought it through.
In case people are wondering why on earth you'd want to do this sort of
thing consider lat/lon positions. Your GPS doesn't suddenly become more
accurate as you near the meridian.
0.123456W is the same accuracy as 100.123456W. If you output 0.123456
and then 100.124 then you're doing something very wrong. Reals are the
natural representation to use to store these numbers too.
K