[英]using stringstream to print a rounded floating point number
i have floating point variables "lmin" and "lmax". 我有浮点变量“lmin”和“lmax”。 i wish to display only 4 significant digits. 我希望只显示4位有效数字。 i am currently using something i have found online of the form ... 我目前正在使用我在网上找到的表格......
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);
where "output" is simply a function i wrote to parse the string and print it to the screen. 其中“输出”只是我编写的一个函数,用于解析字符串并将其打印到屏幕上。 the important point, is how do i print only a ROUNDED version of lmin and lmax to ss? 重要的一点是,我如何只打印一个ROUNDED版本的lmin和lmax到ss?
Use std::setprecision
to specify the number of digits after the decimal point. 使用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;
}
Output: 输出:
12.3457
在插入输出之前,只需使用ss.precision( 4 )
或ss << std::setprecision( 4 )
ss.precision( 4 )
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.