I have tested the following code to verify some simple numerical outputs when std::setprecision
is used in C++:
double f1 = 3.1415;
std::cout << std::setprecision(4) << f1 << '\n';
double f2 = 1.2345;
std::cout << std::setprecision(4) << f2 << '\n';
The corresponding outputs are:
3.142
1.234
Why is 1.234 not being rounded to 1.235? Furthermore, if we change f2
to 1.2315, then the rounding in the output does happen, and the output is 1.232. Is there any rule of thumb to follow when using setprecision
to format the output of numeric values?