Understanding the C++ general floating point formatting

  Kiến thức lập trình

I’m sorry if this has already been posted before. I’ve started reading the book “The C++ standard library – a tutorial and reference” by Nicolai M. Josuttis.

I’m currently on the chapter Chapter 15: Input/Output Using Stream Classes.
At the 15.7.6 Floating-Point Notation part. (For my version of the book. Your version might slightly differ)

There is this table 15.27 trying to explain how the general formatting works for some numbers. General formatting is supposed to be the format that is applied when none of the fixed or 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 formated and printed depending on the precision vamlue assigned to the output stream.
For example,
std::cout << std::precision(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 significants digits higher than the precision value …

Could someone explain to me please the process taken by the stream to ouput that value ?
Thanks.

I was expecting it to print 0.01 instead of 0.012

New contributor

anthonyNk is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

LEAVE A COMMENT