tags:

views:

122

answers:

2

Possible Duplicate:
Rounding Number to 2 Decimal Places in C

I'm currently learning c++ on a linux machine. I've got the following code for rounding down or up accordingly but only whole numbers. How would I change this code to round to the hundredths place or any other decimal? I wouldn't ask if I didn't try looking everywhere already :( and some answers seem to have a ton of lines for what seems to be a simple function!

double round( double ){
return floor(value + 0.5 );
}
+4  A: 

Try

double round( double value )
{
    return floor( value*100 + 0.5 )/100;
}

to round to two decimal places.

Martin B
Note, that this will not work when mantissa has large enough value.
Kirill V. Lyadvinsky
@Kirill Why not?
Tek
@Tek: I think Kirill means that if the exponent (not the mantissa) is too large, such that `value*100` is greater than `numeric_limits<double>::max()`, then the calculation will overflow and give either a result of infinity, or a floating-point exception.
Mike Seymour
@Mike: Oh I see, thanks for the clear up!
Tek
Last time I checked, numeric_limits<double>::max() is about 2^300. It takes a large, large, large value to overflow a double.
DeadMG
If the number if sufficiently large, then you don't have to round it anymore: The rounded value is not distinguishable from the original value.
Luther Blissett
+2  A: 

To do it generically, use the same function you've got, but shift the input up or down some decimals:

double round( double value, int precision )
{
    const int adjustment = pow(10,precision);
    return floor( value*(adjustment) + 0.5 )/adjustment;
}

(Note that you'll have to #include <math.h> or #include <cmath> to use the pow function. If you want to write out a (less powerful) pow for this situation, you could try somrething like:

int intpow(int value, int power)
{   
    int r = 1;
    for (int i=0; i<power; ++i) r *= value;
    return r;
}

[EDIT @ Ben Voigt's comment] only calculated the adjustment once.

Scott Stafford
It's unnecessary to calculate `10**precision` twice like that.
Ben Voigt
Tek