I think that your problem is that precision()
sets the precision used in future stream insertion operations, not when generating the final string to present. That is, by writing
ta << a;
tb << b;
tc << c;
ta.precision(2);
tb.precision(2);
tc.precision(2);
You're setting precision
too late, as the first three lines have already converted the floating point numbers to strings using the default precision.
To fix this, try changing the order in which you execute these statements to
ta.precision(2);
tb.precision(2);
tc.precision(2);
ta << a;
tb << b;
tc << c;
This will cause the writes into the stringstream
to use your custom precision rather than the existing defaults.
However, the effect of the precision
modifier is only meaningful if you explicitly tell the stream that you want to use either fixed-precision or scientific notation for output. To do this, you can use either the fixed
or scientific
modifiers:
ta.precision(2);
tb.precision(2);
tc.precision(2);
ta << fixed << a;
tb << fixed << b;
tc << fixed << c;
This will correctly display the appropriate number of digits.
On a related note, you don't need to use three stringstream
s to accomplish your goal. You can just use one:
std::stringstream t;
t.precision(2);
t << fixed << a << '\n' << b << '\n' << c << '\n';
std::string out = t.str();
3.0
rather than3.00
– Kierkegaard