Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding off floats with ostringstream

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.

like image 636
boom Avatar asked Sep 20 '10 04:09

boom


1 Answers

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();
like image 93
yadab Avatar answered Oct 14 '22 19:10

yadab