Handout - Floating point output format

Unless you tell your C++ program otherwise, floating point values will be output according to default output settings. For example, large floating point values will be output in scientific notation, so that a number like 123456789.5 may be output as 1.234567E+08. Also, if the floating point number is a whole number, C++ doesn't print the decimal point. So 96.0 prints as 96 .

To change these default actions, the programmer should include the following two statements in the program before any floating point output occurs:

   cout.setf(ios::fixed, ios::floatfield);

The first statement indicates that standard notation should be used rather than scientific notation. The second statement forces C++ to show the decimal point for all floating point numbers. Don't worry about how these work right now, just copy them exactly as they appear above into your programs that use floating point numbers.

Another useful formatting option makes use of the setprecision manipulator, which controls the number of decimal places (digits to the right of the decimal point) that are displayed. The parameter to setprecision specifies the desired number of decimal places. The following statements:

   float num=15.839;
   cout << "num = " << setprecision(2) << num;

produce the output

   num = 15.84

Finally, the manipulator setw ("set width") is used to control the number of output columns the next data item will occupy when it is output. setw is used for int and string data as well as for floating point data. Here is an example of the use of setw:

   int x = 1528;
   cout << setw(8) << x;

The output produced by these two statements would consist of four spaces followed by the four digits 1528 (a total of 8 output columns).