Set and return the current format precision.
streamsize precision() const streamsize precision(streamsize prec)
Use the precision() function with floating point numbers to limit the number of digits in the output. You may use precision() with scientific or non-scientific floating point numbers. You may use the overloaded precision() to retrieve the current precision that is set.
With the flag ios::floatfield set, the number in precision refers to the total number of significant digits generated. If the settings are for either ios::scientific or ios::fixed then the precision refers to the number of digits after the decimal place.
This means that ios::scientific will have one more significant digit than ios::floatfield, and ios::fixed will have a varying number of digits.
setprecision()
#include <iostream> #include <cmath> const double pi = 4 * std::atan(1.0); int main() { using namespace std; double TenPi = 10*pi; cout.precision(5); cout.unsetf(ios::floatfield); cout << "floatfield:\t" << TenPi << endl; cout.setf(ios::scientific, ios::floatfield); cout << "scientific:\t" << TenPi << endl; cout.setf(ios::fixed, ios::floatfield); cout << "fixed:\t\t" << TenPi << endl; return 0; }
Result:
floatfield: 31.416 scientific: 3.14159e+01 fixed: 31.41593