4

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 );
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Tek
  • 2,888
  • 5
  • 45
  • 73

2 Answers2

7

Try

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

to round to two decimal places.

Martin B
  • 23,670
  • 6
  • 53
  • 72
  • 4
    Note, that this will not work when mantissa has large enough value. – Kirill V. Lyadvinsky Jul 13 '10 at 12:54
  • 1
    @Tek: I think Kirill means that if the exponent (not the mantissa) is too large, such that `value*100` is greater than `numeric_limits::max()`, then the calculation will overflow and give either a result of infinity, or a floating-point exception. – Mike Seymour Jul 13 '10 at 13:23
  • Last time I checked, numeric_limits::max() is about 2^300. It takes a large, large, large value to overflow a double. – Puppy Jul 13 '10 at 14:23
  • 1
    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. – Nordic Mainframe Jul 13 '10 at 14:34
3

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
  • 43,764
  • 28
  • 129
  • 177
  • 3
    It's unnecessary to calculate `10**precision` twice like that. – Ben Voigt Jul 13 '10 at 12:55
  • I would like to add that: pow(10,precision) should be: const int adjustment = pow((double)10,precision); I messed around with my Linux compiler and although the former worked, when I tried to cross-compile the same code to windows it gives a call overload on pow(int,int&) as "ambiguous". Turns out 10 (base) should be a floating point value and not an int. – Tek Jul 14 '10 at 07:44