我有浮点变量“lmin”和“lmax”。我希望只显示 4 位有效数字。我目前正在使用我在网上找到的表格...
string textout;
stringstream ss;
ss << lmin;
textout = ss.str();
output(-0.5, -0.875, textout);
ss.str("");
ss << lmax;
textout = ss.str();
output(0.2, -0.875, textout);
其中“输出”只是我编写的一个函数,用于解析字符串并将其打印到屏幕上。重要的一点是,我如何只将 lmin 和 lmax 的 ROUNDED 版本打印到 ss?
最佳答案
使用std::setprecision
指定小数点后的位数。
#include <sstream>
#include <iostream>
#include <iomanip>
int main()
{
double d = 12.3456789;
std::stringstream ss;
ss << std::fixed << std::setprecision( 4 ) << d;
std::cout << ss.str() << std::endl;
}
输出:
12.3457
关于c++ - 使用 stringstream 打印四舍五入的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7734609/