我有一个问题,从浮点型转换为c++字符串使用ostringstream。这是我的台词:
void doSomething(float t)
{
ostringstream stream;
stream << t;
cout << stream.str();
}当t的值为-0.89999时,它会舍入为-0.9,但当它的值为0.0999或小于此值时,例如1.754e-7,它就会打印出来,而不会舍入。解决这个问题的办法是什么?
发布于 2010-09-20 12:51:34
您需要使用precision设置ostringstream的精度
e.g
stream.precision(3);
stream<<fixed; // for fixed point notation
//cout.precision(3); // display only
stream << t;
cout<<stream.str();发布于 2010-09-20 12:49:48
如果您想要显示特定数量的有效数字,请尝试使用setprecision(n),其中n是您想要的有效数字数量。
#include <iomanip>
void doSomething(float t)
{
ostringstream stream;
stream << std::setprecision(4) << t;
cout << stream.str();
}发布于 2010-09-20 13:25:54
如果您希望使用定点而不是科学记数法,请使用std::fixed
stream << std::fixed << t;此外,您可能想要设置前面提到的精度。
https://stackoverflow.com/questions/3748749
复制相似问题