Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using stringstream to print a rounded floating point number

i have floating point variables "lmin" and "lmax". i wish to display only 4 significant digits. i am currently using something i have found online of the form ...

string textout;
stringstream ss;

ss << lmin;
textout = ss.str();
output(-0.5, -0.875, textout);

ss.str("");
ss << lmax;
textout = ss.str();
output(0.2, -0.875, textout);

where "output" is simply a function i wrote to parse the string and print it to the screen. the important point, is how do i print only a ROUNDED version of lmin and lmax to ss?

like image 890
drjrm3 Avatar asked Oct 12 '11 02:10

drjrm3


2 Answers

Use std::setprecision to specify the number of digits after the decimal point.

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

int main()
{
  double d = 12.3456789;
  std::stringstream ss;

  ss << std::fixed << std::setprecision( 4 ) << d;

  std::cout << ss.str() << std::endl;
}

Output:

12.3457
like image 121
Praetorian Avatar answered Oct 07 '22 07:10

Praetorian


Simply use ss.precision( 4 ) or ss << std::setprecision( 4 ) before inserting the output.

like image 28
Potatoswatter Avatar answered Oct 07 '22 08:10

Potatoswatter