The setprecision() function can display numbers based on significant digits or number of decimals.
But I have found a problem using this. In particular, when I start using the "fixed" parameter to display based on decimal numbers accordingly, subsequent uses of setprecision() continue to display numbers based on decimal numbers, regardless of whether I re-specify the absence/presence of the "fixed" parameter later on.
The problem code is as follows:
#include <iostream> #include <iomanip> using namespace std; int main () { float fValue = 123.456789; cout << "123.456789 float type at 1 significant digit:" << endl; cout << setprecision(1) << fValue << endl << endl; double dValue = 123.456789; cout << "123.456789 double type at 1 decimal numbers:" << endl; cout << fixed << setprecision(1) << dValue << endl << endl; long double lValue = 123.456789876543210; cout << "123.456789876543210 long double type at 1 significant digit:" << endl; cout << setprecision(1) << lValue << endl << endl; } Output is shown unexpectedly as:
123.456789 float type at 1 significant digit: 1e+002 123.456789 double type at 1 decimal numbers: 123.5 123.456789876543210 long double type at 1 significant digit: 123.5 Output is expected to be shown as:
123.456789 float type at 1 significant digit: 1e+002 123.456789 double type at 1 decimal numbers: 123.5 123.456789876543210 long double type at 1 significant digit: 1e+002
std::fixedwill makestd::setprecision(1)print exactly 1 decimal place.scientific, the precision is the number of significant digits. Withfixed, the precision is the number of decimals. (You probably want to look for better tutorials.)