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
Based on the small comments I have found the answer (and some misinterpretation of the function on my part, in my original unvetted/unedited question). As you know from above, the problem transformed into a problem of not being able to change back from using the "fixed" parameter, to which one prophetic comment pointed to resetting some other parameter to solve it.
The solution code is as follows:
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
const auto default_precision{std::cout.precision()};
float fValue = 123.456789;
cout << "123.456789 float type at 1 significant digit:" << endl;
cout << defaultfloat << setprecision(default_precision);
cout << setprecision(1) << fValue << endl;
double dValue = 123.456789;
cout << "123.456789 double type at 1 decimal number:" << endl;
cout << defaultfloat << setprecision(default_precision);
cout << fixed << setprecision(1) << dValue << endl;
long double lValue = 123.456789876543210;
cout << "123.456789876543210 long double type at 1 significant digit:" << endl;
cout << defaultfloat << setprecision(default_precision);
cout << setprecision(1) << lValue << endl;
}
Also, fixed and setprecision are interchangeable, such that:
cout << fixed << setprecision(1) << dValue << endl;
is equal to:
cout << setprecision(1) << fixed << dValue << endl;