Reputation: 23098
Like the question says. Converting to / from the (truncated) string representations can affect their precision. But storing them in other formats like pickle makes them unreadable (yes, I want this too).
How can I store floating point numbers in text without losing precision?
Upvotes: 7
Views: 2930
Reputation: 27321
pickle.dumps
will do it, but I believe float(str(floatval)) == floatval
too -- at least on the same system...
Upvotes: -1
Reputation: 18187
I'd suggest using the builtin function repr()
. From the documentation:
repr(object) -> string
Return the canonical string representation of the object. For most object types, eval(repr(object)) == object.
Upvotes: 3
Reputation: 799150
Store it in binary or a power thereof.
>>> (3.4).hex()
'0x1.b333333333333p+1'
>>> float.fromhex('0x1.b333333333333p+1')
3.4
Upvotes: 8