2

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?

That is, I want 1.F to be "1.0" and 2.002f to be "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. The precision is fixed for these.

Thanks.

Tim
  • 2,708
  • 1
  • 18
  • 32
  • Good question, and I assume you're asking about actual normalized numbers outside of bit patterns that represent [denormals and infinity and NaNs](http://www.randelshofer.ch/fhw/gri/float.html)? – Jens Jul 07 '15 at 00:01
  • 1
    Related question: [What is the maximum length in chars needed to represent any double value?](http://stackoverflow.com/questions/1701055/what-is-the-maximum-length-in-chars-needed-to-represent-any-double-value) – Jens Jul 07 '15 at 00:06
  • I think this might help: [std::numeric_limits::digits10](http://en.cppreference.com/w/cpp/types/numeric_limits/digits10) – Galik Jul 07 '15 at 00:25
  • One cannot represent `2.002` exactly as `float` or `double`. For `float` case something like `2.0020000934600830078125` is actually stored. – n0rd Jul 07 '15 at 00:25
  • Also, how do you want to numbers like `1e-32` to be represented? If it does not have to be human readable I would vote for dumping `float`'s bytes as hex. – n0rd Jul 07 '15 at 00:29
  • I would strongly advise using hexfloats if you can: not only are they assured to be lossless, but they are significantly (often up to 10x) faster to read/write. – Simon Byrne Jul 07 '15 at 10:20

1 Answers1

2

I have to do exactly that a lot, i.e., what you are trying to do. My solution is to use something like this:

char buf[32];
sprintf(buf, "%.15f", v);
TrimTrailingZeros(buf);
Logicrat
  • 4,438
  • 16
  • 22