Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
Miscellaneous
IOstream Library
manipulators
classes:
filebuf
fstream
ifstream
ios
iostream
ios_base
istream
istringstream
ofstream
ostream
ostringstream
streambuf
stringbuf
stringstream
objects:
cerr
cin
clog
cout
types:
fpos
streamoff
streampos
streamsize
manipulators
boolalpha
dec
endl
ends
fixed
flush
hex
internal
left
noboolalpha
noshowbase
noshowpoint
noshowpos
noskipws
nounitbuf
nouppercase
oct
resetiosflags
right
scientific
setbase
setfill
setiosflags
setprecision
setw
showbase
showpoint
showpos
skipws
unitbuf
uppercase
ws


setprecision

manipulator function
<iomanip>
smanip setprecision ( int n );

Set decimal precision

Sets the decimal precision to be used by output operations.

Behaves as if a call to the stream's member ios_base::precision with n as argument was made.

The decimal precision determines the maximum number of digits to be written on insertion operations to express floating-point values. How this is interpreted depends on whether the floatfield format flag is set to a specific notation (either fixed or scientific) or it is unset (using the default notation, which is neither fixed nor scientific):

  • On the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display in total counting both those before and those after the decimal point. Notice that it is not a minimum and therefore it does not pad the displayed number with trailing zeros if the number can be displayed with less digits than the precision.
  • In both the fixed and scientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if this includes trailing decimal zeros. The number of digits before the decimal point does not matter in this case.

This manipulator is declared in header <iomanip>, along with the other parameterized manipulators: resetiosflags, setiosflags, setbase, setfill and setw. This header file declares the implementation-specific smanip type, plus any additional operator overload function needed to allow these manipulators to be inserted and extracted to/from streams with their parameters.

Parameters

n
New value for the decimal precision.

Return Value

Unspecified. This function should only be used as a stream manipulator.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// setprecision example
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
  double f =3.14159;
  cout << setprecision (5) << f << endl;
  cout << setprecision (9) << f << endl;
  cout << fixed;
  cout << setprecision (5) << f << endl;
  cout << setprecision (9) << f << endl;
  return 0;
}


The execution of this example displays something similar to:
3.1416
3.14159
3.14159
3.141590000

See also