8

I have an issue regarding conversion from float to c++ string using ostringstream. Here is my line:

void doSomething(float t)
{
    ostringstream stream; 
    stream << t;
    cout << stream.str();
}

when t has value -0.89999 it is round off to -0.9, but when it's value is 0.0999 or lesser than this say 1.754e-7, it just prints without round off. what can be the solution for this.

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
boom
  • 5,856
  • 24
  • 61
  • 96

4 Answers4

17

You need to set the precision for ostringstream using precision

e.g

stream.precision(3);
stream<<fixed;    // for fixed point notation
//cout.precision(3); // display only
stream << t;

cout<<stream.str();
yadab
  • 2,063
  • 1
  • 16
  • 24
  • i got solution for 0.0999, but for the number of 7.9e-08 i am still getting the same. so what can be the solution for this. – boom Sep 20 '10 at 05:01
  • you need to set precision to the stream itself. i.e. stream.precision(3); – yadab Sep 20 '10 at 05:11
  • i am doing the same. here is my code:ostringstream stream; stream.precision(1); stream << t; cout << endl<<"Value:"<< stream.str(); – boom Sep 20 '10 at 05:20
  • okay, use a fixed precision. e.g, stream.precision(8); stream << fixed; stream << t; cout << endl<<"Value:"<< stream.str(); – yadab Sep 20 '10 at 05:31
  • What is the default precision for ostringstream? – stephanmg Feb 11 '20 at 00:44
7

If you want a particular number of significant figures displayed try using setprecision(n) where n is the number of significant figures you want.

#include <iomanip>

void doSomething(float t)
{
    ostringstream stream; 
    stream << std::setprecision(4)  << t;
    cout <<  stream.str();
}
sbi
  • 219,715
  • 46
  • 258
  • 445
shuttle87
  • 15,466
  • 11
  • 77
  • 106
2

If you want fixed-point instead of scientific notation, use std::fixed:

stream << std::fixed << t;

Additionally you might want to set the precision as mentioned.

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
0

Use setprecision:

stream << setprecision(5) <<t ;

Now, your string stream.str() will be of the required precision.

Jacob
  • 34,255
  • 14
  • 110
  • 165
  • i got solution for 0.0999, but for the number of 7.9e-08 i am still getting the same. so what can be the solution for this. – boom Sep 20 '10 at 05:03