Re: float to string to float, with first float == second float
On Oct 6, 11:34 am, "Francesco S. Carta" <entul...@gmail.com> wrote:
On 6 Ott, 11:16, Carsten Fuchs <CarstenFu...@T-Online.de> wrote:
I would like to serialize a float f1 to a string s, then
unserialize s back to a float f2 again, such that:
* s is minimal (use only the precision that is required)
and preferably in decimal notation,
* f1==f2 (exact same value after the roundtrip)
(The first property is for human readers and file size, the
second is for data integrity.)
I've seen algorithms for this in the past. (Perhaps "How to
print floating point numbers accurately", by Guy Steele, but I'm
Here is my implementation:
std::string serialize(float f1)
for (unsigned int prec=6; prec<10; prec++)
ss << f1;
ss >> f2;
if (f2==f1) break;
It seems to work very well, and I found that in my
application 65% to 90% of the float numbers serialized this
way exit the loop in the first iteration.
You don't always need six digits---for the value 1.0, one digit
is enough. And if the floating point format is IEEE, seven
digits are always enough.
However, I was wondering if there is a shorter and/or more
elegant way of implementing this, using either C++ streams,
C printf-functions, or any other technique available in C++.
There are certainly more efficient means, but the ones I know
require reimplementing the conversion function itself, rather
than using the one present in the library.
There are a couple of problems with your code.
First, you should never compare floats or doubles for equality
Why not? And what should he do instead? He wants to know if
the two values are exactly equal.
Secondarily, extracting (>>) non-character data (integers,
doubles and so on) from streams can hang.
Since when? A correct implementation of stringstream will never
hang. (A correct implementation of an fstream can hang if the
"file" is actually a device which can hang, but that's beyond
the power of the library to control.)