在 C++ 中将科学记数法转换为十进制

Rob*_*ley 5 c++ scientific-notation decimal

我希望能够在我的代码中的所有情况下以十进制输出而不是科学输出。

如果我有 122041e+08 那么我希望它显示为 122041000

如果我有 4.6342571e+06 那么我希望它显示为 4634257.1

... 等等。

使用我的代码,4.6342571e+06 的输出是 4634257.100000

void conversion(double counts)
{
  std::ostringstream ss;
  ss << std::fixed << counts;
  std::cout << ss.str() << " MeV";
}
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释为什么它会在末尾添加 0 以及是否可以删除它们。

Oli*_*rth 6

您可以使用std::setprecision


jup*_*p0r 2

输出字符串流中有一个称为precision的方法。您可以使用它来调整逗号后的位数。默认为 6,缺失的数字用 0 填充(因此名称固定)。为了实现4634257.1显示,将精度设置为1:

void conversion(double counts)
{
  std::ostringstream ss;
  ss.precision(1);
  ss << std::fixed << counts;
  std::cout << ss.str() << " MeV";
}
Run Code Online (Sandbox Code Playgroud)