Section 7 - Formatting Numbers
3A.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:

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:

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:
Flag | Meaning |
---|---|
ios::fixed | display output as fixed point |
ios::hex | display output as hexadecimal |
ios::dec | display output as decimal |
ios::scientific | display output using scientific notation |
Here is a reference for more flags: http://msdn.microsoft.com/en-us/library/d2a1929w%28v=vs.110%29.aspx
