我有一个关于使用ostringstream从float转换为c ++字符串的问题。这是我的专栏:
void doSomething(float t)
{
ostringstream stream;
stream << t;
cout << stream.str();
}
当t的值为-0.89999时,它会向下舍入为-0.9,但是当它的值为0.0999或小于此值时为1.754e-7时,它只是打印而不是舍入。什么可以解决这个问题。
答案 0 :(得分:15)
您需要使用precision
例如
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)
答案 3 :(得分:0)