8

我有一个关于使用 ostringstream 从浮点数转换为 C++ 字符串的问题。这是我的台词:

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

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

4

4 回答 4

17

您需要使用 ostringstream 设置精度precision

例如

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

cout<<stream.str();
于 2010-09-20T04:51:34.297 回答
7

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

#include <iomanip>

void doSomething(float t)
{
    ostringstream stream; 
    stream << std::setprecision(4)  << t;
    cout <<  stream.str();
}
于 2010-09-20T04:49:48.140 回答
2

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

stream << std::fixed << t;

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

于 2010-09-20T05:25:53.643 回答
0

使用setprecision

stream << setprecision(5) <<t ;

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

于 2010-09-20T04:57:31.160 回答