round() for float in C++

后端 未结 22 1875
时光取名叫无心
时光取名叫无心 2020-11-22 03:01

I need a simple floating point rounding function, thus:

double round(double);

round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1

I can find

22条回答
  •  天命终不由人
    2020-11-22 03:31

    You could round to n digits precision with:

    double round( double x )
    {
    const double sd = 1000; //for accuracy to 3 decimal places
    return int(x*sd + (x<0? -0.5 : 0.5))/sd;
    }
    

提交回复
热议问题