【问题标题】:using stringstream to print a rounded floating point number使用 stringstream 打印四舍五入的浮点数
【发布时间】:2011-10-12 02:26:07
【问题描述】:

我有浮点变量“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?

【问题讨论】:

标签: c++ string stringstream


【解决方案1】:

使用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

【讨论】:

  • 虽然这几乎完美地回答了我的问题,但我要把信封推得更远一点,问是否有一种简单的方法可以将其打印为科学记数法?如果我有 12.3457,我只想要 4 位,不一定是小数点后 4 位,所以我想要 12.34(或等效地,1.234e+1)
  • @Laurbert515 去掉std::fixed 部分,默认是科学的:)。或者你可以明确地使用std::scientific
  • @Laurbert515 似乎我错了默认部分,对不起。 ideone.com/a07Z0
【解决方案2】:

在插入输出之前只需使用ss.precision( 4 )ss &lt;&lt; std::setprecision( 4 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多