Rounding off floats with ostringstream

我与影子孤独终老i 提交于 2019-12-12 10:37:09

问题


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.


回答1:


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();



回答2:


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();
}



回答3:


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.




回答4:


Use setprecision:

stream << setprecision(5) <<t ;

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



来源:https://stackoverflow.com/questions/3748749/rounding-off-floats-with-ostringstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!