Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a number from stringstream to string with a set precision

I would like to obtain a number from stringstream and set it to 5 significant figures. How do I do this? So far, this is what I have managed to come up with:

double a = 34.34566535
std::stringstream precisionValue;
precisionValue.precision(6) << a << std::endl;

However, this is not compiling. Thanks.

like image 299
programmingNoob Avatar asked Nov 29 '22 14:11

programmingNoob


2 Answers

It doesn't compile because ios_base::precision() returns streamsize (it's an integral type).

You can use stream manipulators:

precisionValue << std::setprecision(6) << a << std::endl;

You'll need to include <iomanip>.

like image 93
jrok Avatar answered Dec 14 '22 23:12

jrok


std::stringstream::precision() returns a streamsize, not a reference to the stream itself, which is required if you want to sequence << operators. This should work:

double a = 34.34566535;
std::stringstream precisionValue;
precisionValue.precision(6);
precisionValue << a << std::endl;
like image 34
Zyx 2000 Avatar answered Dec 15 '22 00:12

Zyx 2000