Is there a better way to round a floating point number with n decimal places in C ++?

I knew that the general way is to multiply 10 ^ n and then divide 10 ^ n. Round the float with one digit number But due to the double precision accuracy problem, I found that the solution above does not fully work for my case:

0.965 * 0.9 = 0.8685

std::round(0.8685 * 1000) / 1000 = 0.869
// expects it to be 0.869
std::round(0.965 * 0.9 * 1000) / 1000 = 0.868

If I want to get 0.869from std::round(0.965 * 0.9 * 1000) / 1000directly, I need to change the operator to

std::round((0.965 * 0.9 + std::numeric_limits<double>::epsilon()) * 1000) / 1000 = 0.869

Is there an easier way to round without adding epsilonfor each calculation?

Edit: The problem is that intuitively the value std::round(0.965 * 0.9 * 1000) / 1000should be 0.869(because 0.965 * 0.9 = 0.8685), but actually it gives 0.868. I want to find a general way to get an exact mathematical value with an accuracy of 3 digits.

+6
2

, , printf ostream.

, . , IEEE754 double 0.965

0.96499999999999996891375531049561686813831329345703125

?. , , "" , std::numeric_limits<double>::epsilon().

std::round , - , x.5 x , ​​ . , , .

, std::round(x * y) / y, , , .

, , , . . ++

+7

:

#include <iostream>
#include <limits>
#include <cmath>

using namespace std;

double roundDec(double var) {
    var = round((var + std::numeric_limits<double>::epsilon()) * 1000) / 1000;

    return var;
}

int main() {

    double var = 0.8685;

    cout << roundDec(var);

    return 0;
}
0

All Articles