precision.cpp

The behavior of the precision function depends on the current settings of the floating point flags and the kind of data that is output: Setting the precision has no effect on how integers are displayed bit it does effect how floating point values (i.e., floats or doubles) are displayed. If both the fixed and the scientific flags are off, then precision sets the number of significant digits appearing in the output; if either flag is on, then it sets the number of digits appearing after the decimal point. The code in the following program is separated into four major blocks; the output is also grouped into corresponding blocks to make it easier to see the impact of the formatting statements.

#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
	cout << 123456789 << endl;
	cout << 123456789. << endl;
	cout << M_PI << endl;
	cout << endl;

	cout.precision(2);
	cout << 123456789 << endl;
	cout << 123456789. << endl;
	cout << M_PI << endl;
	cout << endl;

	cout.setf(ios::fixed);
	cout << 123456789 << endl;
	cout << 123456789. << endl;
	cout << M_PI << endl;
	cout << endl;

	cout.unsetf(ios::fixed);

	cout.setf(ios::scientific);
	cout << 123456789 << endl;
	cout << 123456789. << endl;
	cout << M_PI << endl;

	return 0;
}

Output:

123456789
1.23457e+008
3.14159

123456789
1.2e+008
3.1

123456789
123456789.00
3.14

123456789
1.23e+008
3.14e+000
  1. Default formatting: large floating point numbers are automatically written in scientific notation while small floating point number are not.
  2. Precision set to 2: floating point numbers displayed with two significant digits: 1.2 and 3.1.
  3. Precision set to 2 and fixed flag set: two digits displayed after the decimal point.
  4. Precision set to 2 and scientific flag set: all floating point numbers displayed in scientific notation (not just large numbers) with two digits after the decimal point.