Jesvin Jose
Jesvin Jose

Reputation: 23098

How to store a floating point number as text without losing precision?

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

Answers (3)

thebjorn
thebjorn

Reputation: 27321

pickle.dumps will do it, but I believe float(str(floatval)) == floatval too -- at least on the same system...

Upvotes: -1

silvado
silvado

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

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

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

Related Questions