c++ - 如何避免`std::to_string()`将一个非常小的双数变为0?
问题描述
我需要将非常小的双数存储为字符串格式,然后再将它们反转。但是,当我尝试运行std::to_string()
像4.7816457028269855e-143
then 这样的小数字时,它只是将其设为 0。
在转换浮点值及其链接副本时,我提到了设置 std::to_string 的精度。但是将精度设置为一个非常大的数字会在所有平台上解决这个问题吗?
如何解决这个问题?
使用任何替代品to_string()
都可以。
解决方案
如前所述,使用 是不可能实现的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/。
推荐阅读
- mongodb - 在 pymongo 中触发
- c# - 如何在 WASM 运行时中运行 UnitTest
- laravel - 存储多态 belongsTo 关系的最佳实践
- r - 删除数据框中包含特定值的因子列
- firebase - > 任务:react-native-async-storage_async-storage:parseDebugLocalResources FAILED
- windows - 我想要一个批处理文件来删除绝对路径位置 (F:\work) 中的所有文件,但名为“txt1.txt”和“txt2.txt”的两个文件除外
- python - 如何在 MongoDB 保存中更改对象的行为?
- opengl - 为什么我在多边形之间有这种奇怪的接缝?
- angular - Angular 升级并添加模块联合插件后,浏览器未加载应用程序
- css - 将溢出装入父容器