Section 7 - Formatting Numbers on the Console

This is a short reference for number formatting for screen (or other stream) output.  You can treat it as a reference and use it as needed.  However, don't miss the "Prevent Point Loss" section at the end of the page.

1B.7.1 Number Format

What happens if we run this program?

#include <iostream>
using namespace std;

int main()
{
    double x = 1, y = 3, z;

    z = x/y;
    cout << x << " / " << y << " = " << z << endl;
}

The answer is, we get this:

console shot

Why did the C++ give us six decimal places for the answer?  The correct mathematical answer has a string of 3s going on forever.  We might have wanted more accuracy. Or less: maybe we were talking about money?  So how do we get C++ to produce exactly the number of places we desire?  Answer: We do it through some method calls that we have at our disposal.  Here is one solution:

cout.setf(ios::fixed);
cout.precision(12);

These are two funny looking method calls, so let me try to explain them simply.  The first one tells C++ that we want to have our numbers displayed in so-called fixed-format.  That means there will be a decimal point and a fixed number of digits to the right of the decimal.  The second method call asks for 12 places.  We could have asked for 2 or any other number of digits to be displayed. 

If you place these two lines anywhere before your cout, you will have a different result:

console shot

Notice that we are now getting 12 places even where there is no need for them all.  That's what fixed means.

So, what other options do we have?  Tons.  The first method call, cout.setf() takes many constant flags, a few of the useful ones are:

Useful Flags for setf()
Flag Meaning
ios::fixed display output as fixed point
ios::hex display output as hexidecimal
ios::noshowpoint do not display decimal point on numbers that have no fractional part
ios::dec display output as decimal
ios::scientific display output using scientifc notation

Here is a reference for more flags: https://msdn.microsoft.com/en-us/library/d2a1929w%28v=vs.110%29.aspx

coins

Prevent Point Loss

Here are some point-saving rules that will apply to the entire course, many of which are review from CS 2A.

guy with blackboard


This has been a fun introduction to your second C++ course.  In the next 11 weeks you will become seriously capable C++ programmers.  I hope that you enjoy the ride.