4

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.

programmingNoob
  • 141
  • 2
  • 3
  • 8

4 Answers4

11

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>.

jrok
  • 54,456
  • 9
  • 109
  • 141
6

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;
Zyx 2000
  • 1,625
  • 1
  • 12
  • 18
3

The precision member function returns current precision, not a reference to the stringstream, so you cannot chain the calls as you've done in the snippet.

precisionValue.precision(6);      
precisionValue << a;
std::cout << precisionValue.str() << std::endl;

Or use the setprecision IO manipulator to chain the calls:

precisionValue << setprecision(6) << a;
std::cout << precisionValue.str() << std::endl;
Praetorian
  • 106,671
  • 19
  • 240
  • 328
2

You can use std::setprecision from header <iomanip>

#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>

int main()
{
  double a = 34.34566535;
  std::stringstream precisionValue;
  precisionValue << std::setprecision(6);
  precisionValue << a << std::endl;
  std::cout << precisionValue.str();
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480