c++ - 将 float 转换为字符串而不会丢失精度

标签 c++ c type-conversion

我想在不丢失或添加任何单精度数字的情况下将浮点值存储到字符串中。

例如,如果我的浮点值为 23.345466467 ,我希望我的字符串具有 str = "23.345466467"精确数字。

我尝试使用带有 %f 的 CString 格式函数。它只给出前6个精度。 或者如果我使用 %10 ,如果我的浮点值的精度小于 10,它会增加一些垃圾精度。我想在我的字符串中获取精确的浮点值。如何做到这一点?

最佳答案

请参阅 http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/ 中的详细讨论.

简短的回答是最小精度如下:

printf("%1.8e", d);  // Round-trippable float, always with an exponent
printf("%.9g", d);   // Round-trippable float, shortest possible
printf("%1.16e", d); // Round-trippable double, always with an exponent
printf("%.17g", d);  // Round-trippable double, shortest possible

或者等效地,使用 std::ostream& os:

os << scientific << setprecision(8) << d;    // float; always with an exponent
os << defaultfloat << setprecision(9) << d;  // float; shortest possible
os << scientific << setprecision(16) << d;   // double; always with an exponent
os << defaultfloat << setprecision(17) << d; // double; shortest possible

关于c++ - 将 float 转换为字符串而不会丢失精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4459987/

相关文章:

c - Libcurl 如何不显示所有这些信息

c++ - OpenGL 中的可视化问题(glOrtho 和投影)

c# - silverlight TypeDescriptor.GetConverter 替代品

c# - 如何在 C# 中表示一个数字是长整数还是小数?

c++ - 如何在 multi_index_container 中添加指定的有序唯一索引

c++ - Comparator 可以用来设置新的 key ,不是吗?

c++ - 模板函数中的默认参数值,取决于类型

c++ - 开发环境沙盒

c - nonblocking recv返回0怎么知道是哪种情况?

java - 将 long 转换为 double 并返回时值发生变化