我想在不丢失或添加任何单精度数字的情况下将浮点值存储到字符串中。
例如,如果我的浮点值为 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/