删除科学表示中间的尾随零

  • 本文关键字:中间 表示 删除 c++
  • 更新时间 :
  • 英文 :


我需要以特定的方式格式化双精度校验和。

0.000045->"4.5e-05"

0.0000632->"6.32e-05"

我试过这个:

#include <sstream>
std::stringstream ss;
ss << std::scientific << std::showpoint << value;
return ss.str();

但我在小数点后面有很多零:

"4.500000e-05"

设置精度确实有帮助:

std::stringstream ss;
ss << std::scientific << std::setprecision(3) << std::showpoint << value;
return ss.str();

输出:

"4.500e-05"

但我无法设置精度,因为它取决于输入的数字。

这应该适用于小数字。

std::stringstream ss;
// Resets fixed and set scientific style.
ss.setf(std::ios_base::scientific | std::ios_base::showpoint, std::ios_base::fixed);
ss << value;
return ss.str();  // 4.5e-05 or 6.32e-05

最新更新