c++formattingprecisioniostreamiomanip

How does std::setprecision affect general floating-point formatting?


I am reading "The C++ standard library - a tutorial and reference" by Nicolai M. Josuttis, Chapter 15: Input/Output Using Stream Classes. At 15.7.6 Floating-Point Notation, there is a table explaining how the general formatting works for some numbers.

General formatting is the format that is applied when neither fixed nor scientific notation are picked by the developer.

precision() 421.0 0.0123456789
2 4.2e+02 0.012
6 421 0.0123457.

The table shows how a floating-point number is formatted and printed depending on the precision value assigned to the output stream. For example, std::cout << std::setprecision(2) << 421.0 << std::endl; Will print 4.2e+02

I don't understand why for precision = 2, in the general format, 0.0123456789 prints 0.012 which shows a number of significant digits greater than the precision value. I was expecting it to print 0.01 instead of 0.012


Solution

  • It works correctly because in this case, precision means the amount of significant digits; it's a mathematical term. E.g. in the number 0.00078 there are 2 significant digits - 78. Not to be confused with the number of digits after decimal point (i.e. number of decimal places).