7

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?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
drjrm3
  • 4,474
  • 10
  • 53
  • 91
  • [Possible duplicate](http://stackoverflow.com/questions/3748749/rounding-off-floats-with-ostringstream) – Ayjay Oct 12 '11 at 02:34

2 Answers2

13

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
Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • while this almost perfectly answers my question, i'm going to push the envelop a bit farther and ask if there is a simple way to print it to scientific notation? if i have 12.3457, i will want only 4 digits, not necessarily 4 digits after the decimal, so i would want 12.34 (or equivalently, 1.234e+1) – drjrm3 Oct 12 '11 at 02:41
  • @Laurbert515 Just take out the `std::fixed` part, default is scientific :). Or you can explicitly use `std::scientific` – Praetorian Oct 12 '11 at 02:43
  • @Laurbert515 Seems I was wrong about the default part, sorry. http://www.ideone.com/a07Z0 – Praetorian Oct 12 '11 at 02:49
1

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

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421