how to do Precision with ostrstream

Hi all can you help me in setting precision for the float value

for eg..

1
2
3
4
ostrstream out;
float fvalue = 2.7889

out << fvalue;

if I take the value of out.str() i should be able to get 2.78 only.

Thanks in advance
You should be using ostringstream (in <sstream>) rather than ostrstream these days. ostrstream has been deprecated since C++98 (i.e. 15 years!)

But the correct answer is 2.79, yes?

Andy

value = 2.79


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <iomanip> // for setprecision
#include <sstream> // for ostringstream
using namespace std;

int main()
{
	ostringstream out;

	float fvalue = 2.7889f; // f suffix as it's a float value

	out << setprecision(3);
	out << "value = ";
	out << fvalue;

	cout << out.str() << endl;

	return 0;
}



Last edited on
thanks you andy and ats15
Topic archived. No new replies allowed.