使用ostringstream整理浮动

时间:2010-09-20 04:44:51

标签: c++ rounding stringstream ostringstream

我有一个关于使用ostringstream从float转换为c ++字符串的问题。这是我的专栏:

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

当t的值为-0.89999时,它会向下舍入为-0.9,但是当它的值为0.0999或小于此值时为1.754e-7时,它只是打印而不是舍入。什么可以解决这个问题。

4 个答案:

答案 0 :(得分:15)

您需要使用precision

设置ostringstream的精度

例如

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

cout<<stream.str();

答案 1 :(得分:6)

如果您想显示特定数量的有效数字,请尝试使用setprecision(n),其中n是您想要的有效数字的数量。

#include <iomanip>

void doSomething(float t)
{
    ostringstream stream; 
    stream << std::setprecision(4)  << t;
    cout <<  stream.str();
}

答案 2 :(得分:2)

如果您想要定点而不是科学记数法,请使用std::fixed

stream << std::fixed << t;

此外,您可能希望设置所述的精度。

答案 3 :(得分:0)

使用setprecision

stream << setprecision(5) <<t ;

现在,您的字符串stream.str()将具有所需的精度。