user974967
user974967

Reputation: 2946

C++ rounding behavior

#include <iostream>
#include <iomanip>

int main()
{
    float f = 0.115;

    std::cout << f << std::endl;
    std::cout << std::fixed << std::setprecision(2) << f << std::endl;

    return 0;
}

The output of the above code is:

0.115
0.12

It makes sense that 0.115 is rounded to 0.12. However, when we change f to 0.225 the output is:

0.225
0.22

Why isn't this rounded to 0.23?

Upvotes: 1

Views: 507

Answers (1)

Freyja
Freyja

Reputation: 40814

Your computer can't represent most decimal fractions numbers exactly, since it works with binary numbers. Instead, it tries to find the closest number it can represent, and use that instead.

For instance, my computer represents the following numbers as:

decimal      actual representation
0.115        0.115000002
0.225        0.224999994
0.245        0.245000005
0.335        0.335000008
0.445        0.444999993

By default, C++ will use normal rounding to closest, i.e., digits 5-9 are rounded up and 0-4 are rounded down. Therefore, of the numbers above, 0.115, 0.245 and 0.335 will be rounded up to 0.12, 0.24 and 0.34, while 0.225 and 0.445 will be rounded down to 0.22 and 0.44.

Upvotes: 3

Related Questions