首页 > 解决方案 > 如何避免`std::to_string()`将一个非常小的双数变为0?

问题描述

我需要将非常小的双数存储为字符串格式,然后再将它们反转。但是,当我尝试运行std::to_string()4.7816457028269855e-143then 这样的小数字时,它只是将其设为 0。

在转换浮点值及其链接副本时,我提到了设置 std::to_string 的精度。但是将精度设置为一个非常大的数字会在所有平台上解决这个问题吗?

如何解决这个问题?
使用任何替代品to_string()都可以。

标签: c++floating-pointdoublec++14tostring

解决方案


如前所述,使用 是不可能实现的std::to_string,但是以std::ostringstream足够大的精度输出数字将解决您的问题。

可以使用 C++ 标准库工具以跨平台方式计算所需的精度,特别是std::numeric_limits<T>::max_digits10常量:https ://en.cppreference.com/w/cpp/types/numeric_limits/max_digits10

例如:

std::string to_string_exact(double x) {
  std::ostringstream os;
  os << std::setprecision(std::numeric_limits<double>::max_digits10) << x;
  return os.str();
}

有关一些警告,另请参阅https://possiblywrong.wordpress.com/2015/06/21/floating-point-round-trips/


推荐阅读