0

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?

1 Answers1

1

The comment tells you why. I strongly recommend to read https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

In order to do correct rounding, C++ comes with round() for that but it only round to integer, not arbitrary decimal places. The following can give you 1.235, although a bit ugly:

double f1 = 3.1415;
std::cout << std::setprecision(4) << round(f1*1000)/1000 << '\n';
double f2 = 1.2345;
std::cout << std::setprecision(4) << round(f2*1000)/1000 << '\n';
adrtam
  • 6,991
  • 2
  • 12
  • 27