c++ - 使用 stringstream 打印四舍五入的 float

标签 c++ string stringstream

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

相关文章:

c++ - 具有可变数量参数的函数,这些参数被转换为字符串

c++ - 如何修改此代码以使用函数而不是 lambda?

string - KDB在select/exec语句中串联字符串

c++ - Stringstream 的 Str 方法将不起作用。 (不同类型的串联)(C++)

c++ - luhn算法和C++中的 'digit manipulation'

c++ - 为什么连续的 istream_iter 对象会递增迭代流?

c++ - 原子写入和 volatile 读取

c++ - 链接列表 - 几乎完成,但在某处仍然存在小问题。需要帮助

javascript - 在箭头函数中使用 name=arguments 作为函数参数是个好习惯吗?

java - 将奇偶数与字符串分开