Topic: %6.2f format to cout


Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 1995/04/11
Raw View
In article fk8@darkstar.UCSC.EDU, ray@cse.ucsc.edu (Ray Swartz) writes:
>How would I print a double in the format specified by %.2f?
>
>double x, y;
>// assign x and y some value
>cout << x * y;  // how to format this to %.2f?
>
>According to Teale (C++ IOStreams Handbook), I would use the setprecision
>manipulator that calls the precision member function to set the precision
>
>cout << setprecision(2) << x * y;
>
>Borland C++ 4.5 doesn't do this.  Instead, it treats the precision
>member function as stating the precision of the entire number.  Thus,
>precision(2) tells Borland to print no more than 2 digits.

Either Teale's book has an error or you didn't read it carefully enough.

By default, floating-point gets printf "g"-style formatting, where the
precision means total number of significant digits. To get the printf
"f"-style formatting, you first need to specify "fixed" format:

 cout.setf(ios::fixed, ios::floatfield);
---
Steve Clamage, stephen.clamage@eng.sun.com







Author: ray@cse.ucsc.edu (Ray Swartz)
Date: 1995/04/10
Raw View
How would I print a double in the format specified by %.2f?

double x, y;
// assign x and y some value
cout << x * y;  // how to format this to %.2f?


According to Teale (C++ IOStreams Handbook), I would use the setprecision
manipulator that calls the precision member function to set the precision


cout << setprecision(2) << x * y;

Borland C++ 4.5 doesn't do this.  Instead, it treats the precision
member function as stating the precision of the entire number.  Thus,
precision(2) tells Borland to print no more than 2 digits.

The last standard draft I have (1/94) agrees with Teale.

Is this a Borland bug?  If not, what is the proper way to
print in %.2f format without using printf or sprintf, which
I rather not do.

Ray Swartz