ios_base::precision

http://www.cplusplus.com/reference/iostream/ios_base/precision/

ios_base::precision

public member functionstreamsize precision ( ) const;
streamsize precision ( streamsize prec );


I don't understand wt the function is.
As it's written it is the maximum number of digits that are written into a stream.
The number of written digits is max(precision, availableDigits).
If you set the floatfield to fixed then always "precision" digits are written (missing digits are filled with zeros).

Simply try it for yourself with different combinations of numbers (like 12, 1.23, 1.2345678, 0.00012) and different precisions (0, 5, 10)!
streamsize precision ( ) const;
streamsize precision ( streamsize prec );

Then what do these two sentences mean?
if you call precision without arguments (the first signature) it just returns the current precision.
If you call it with arguments (the second signature) "prec" is used as the new precision and the old precision is returned.

1
2
3
4
5
6
7
8
9
10
11
12
// some other peoples code
cout.precision(5); // precision is now 5
cout << 1.234567890; // prints 1.2345
// Your code, maybe in a function
streamsize previousPrecision = cout.precision(); // called without arguments i.e. "streamsize precision ( ) const"
// previousPrecision contains the value "5"
cout << 1.234567890; // prints 1.2345
streamsize oldPrecision = cout.precision(7); // oldPrecision == 5, active precision is 7
cout << 1.234567890; // prints 1.234567
cout.precision(previousPrecision); // restore previous precision, active precision is now 5
// end of your code
cout << 1.234567890; // prints 1.2345 again 


If you have a piece of code that want's to change precision you should store the precision at the beginning (line 5)
and restore it at the end of use (line 10).
Topic archived. No new replies allowed.