user3142434
user3142434

Reputation: 305

round function returns wrong double estimation

I am trying to round the double up to 3 decimal points but ...

double round_double(double d){
    return round(d * 1000) / 1000;
}

int main() {
    double r = round_double(1.5 * 1.001);
    cout << r << endl;
    return 0; }

When I run it the result is 1.501... Why doesn't it return 1.502? Also when I change the round_double function to look like this:

return floor(d * 1000 + 0.5) / 1000;

It still produces 1.501... Any ideas why?

Upvotes: 2

Views: 165

Answers (1)

Stas
Stas

Reputation: 11771

Because 1.5 * 1.001 doesn't have exact representation in double. It is treated as 1.5014999999999998.

A very common way to fix this problem is to add (subtract) some epsilon value.

Your rounding function with epsilon correction might look like

double round_double(double d)
{
    const double epsilon = 10e-8;
    d = signbit(d) ? d - epsilon : d + epsilon;
    return round(d * 1000) / 1000;
}

Upvotes: 6

Related Questions