How to save a floating point number in the text without losing accuracy?

As in the question. Converting to / from (truncated) string representations can affect their accuracy. But storing them in other formats, such as pickle, makes them unreadable (yes, I want it too).

How can I store floating point numbers in text without losing accuracy?

+7
source share
3 answers

I would suggest using the built-in repr() function. From the documentation:

repr (object) -> string

Returns the canonical string representation of the object. For most types of objects, eval (repr (object)) == object.

+3
source

Store it in binary form or valid.

 >>> (3.4).hex() '0x1.b333333333333p+1' >>> float.fromhex('0x1.b333333333333p+1') 3.4 
+7
source

pickle.dumps will do this, but I believe that float(str(floatval)) == floatval too - in at least one system ...

-one
source

All Articles