Actually, the problem is not setprecision
, it's fixed
. With fixed
you explicitly asked to have a fixed number of digits!
If you use setprecision
without fixed
, it'll do exactly what you are asking for:
#include <iostream>
#include <iomanip>
int main() {
double const number = 123.456789;
for (int i = 0; i != 15; ++i) { std::cout << i << ": " << std::setprecision(i) << number << "\n"; }
return 0;
}
Will output:
0: 1e+02
1: 1e+02
2: 1.2e+02
3: 123
4: 123.5
5: 123.46
6: 123.457
7: 123.4568
8: 123.45679
9: 123.456789
10: 123.456789
11: 123.456789
12: 123.456789
13: 123.456789
14: 123.456789
You can find documentation on the different modes here:
fixed
scientific
hexfloat
defaultfloat
And what you want is defaultfloat
, which as the name implies is the default.