开发者

C++ Rounding to the _nths place [duplicate]

开发者 https://www.devze.com 2023-01-07 03:52 出处:网络
This question already has answers here: How do I restrict a float value to only two places after the decimal point in C?
This question already has answers here: How do I restrict a float value to only two places after the decimal point in C? 开发者_如何转开发 (17 answers) Closed 10 months ago.

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 );
}


Try

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

to round to two decimal places.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消