我有一个关于使用 ostringstream 从浮点数转换为 C++ 字符串的问题。这是我的台词:
void doSomething(float t)
{
ostringstream stream;
stream << t;
cout << stream.str();
}
当 t 的值为 -0.89999 时,它会四舍五入到 -0.9,但是当它的值是 0.0999 或小于 1.754e-7 时,它只会在不四舍五入的情况下打印。什么可以解决这个问题。
我有一个关于使用 ostringstream 从浮点数转换为 C++ 字符串的问题。这是我的台词:
void doSomething(float t)
{
ostringstream stream;
stream << t;
cout << stream.str();
}
当 t 的值为 -0.89999 时,它会四舍五入到 -0.9,但是当它的值是 0.0999 或小于 1.754e-7 时,它只会在不四舍五入的情况下打印。什么可以解决这个问题。
您需要使用 ostringstream 设置精度precision
例如
stream.precision(3);
stream<<fixed; // for fixed point notation
//cout.precision(3); // display only
stream << t;
cout<<stream.str();
如果您想要显示特定数量的有效数字,请尝试使用 setprecision(n) 其中 n 是您想要的有效数字的数量。
#include <iomanip>
void doSomething(float t)
{
ostringstream stream;
stream << std::setprecision(4) << t;
cout << stream.str();
}