[英]c++ formatting float with automatic precision
Is there a standard way of formatting a float (or double) in C++ in decimal with exactly enough precision to parse it back to the same bits?是否有一种标准方法可以在 C++ 中以十进制格式格式化浮点数(或双精度数),并且具有足够的精度以将其解析回相同的位?
That is, I want 1.F
to be "1.0"
and 2.002f
to be "2.002"
.也就是说,我希望
1.F
为"1.0"
, 2.002f
为"2.002"
2.002f
"2.002"
。
For cases, where decimal is inexact another format would be acceptable (scientific or even hex float).对于十进制不精确的情况,另一种格式是可以接受的(科学甚至十六进制浮点数)。 Does such a case exist?
这样的案例存在吗?
All I can find is reference to std::fixed
and std::setprecision
such as this link .我能找到的只是对
std::fixed
和std::setprecision
引用,例如这个链接。 The precision is fixed for these.这些的精度是固定的。
Thanks.谢谢。
I have to do exactly that a lot, ie, what you are trying to do.我必须做很多事情,即你正在尝试做的事情。 My solution is to use something like this:
我的解决方案是使用这样的东西:
char buf[32];
sprintf(buf, "%.15f", v);
TrimTrailingZeros(buf);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.