< previous page page_111 next page >

Page 111
Hi 337132
You can specify a fieldwidth for floating point values just as for integer values. But you must remember to allow for the decimal point in the column count. The value 4.85 occupies four output columns, not three. If x contains the value 4.85, the statement
cout << setw(4) << x << endl
     << setw(6) << x << endl
     << setw(3) << x << endl;
produces the output
4.85
  4.85
4.85
In the third line, a fieldwidth of 3 isn't sufficient, so the field automatically expands to accommodate the number.
There are several other issues involved with output of floating point numbers. First, large floating point values are printed in scientific (E) notation. The value 123456789.5 may print on some systems as
1.234567E+08
Second, if the number is a whole number, C++ doesn't print a decimal point. The value 95.0 prints as
95
Third, you often would like to control the number of decimal places (digits to the right of the decimal point) that are displayed. For example, if you are printing monetary values as dollars and cents, you would prefer the values 12.8 and 16.38753 to print as 12.80 and 16.39.
To address the first two issues, you can include the following two statements in your program before any floating point output takes place:
cout.setf(ios::fixed, ios::floatfield);    // Set up floating point
cout.setf(ios::showpoint);                 //   output format

 
< previous page page_111 next page >