Edit: this is in python 2.7.7
Has anyone come across this? I need to serialise an key-value pair object into a string, in which each key contains a float.
There can be any number of entries (I demonstrate just one, "Test", in this example).
It seems that when evaluating the whole object, Python can add decimals to the value, whereas when we look at those exact same values independantly (outside of the object), they appear "normal".
I need a way to make the final, serialised object contain the original values (0.08 in this case) ; or a means to force them to 2DPs.
userConstraints = {
"test": 0.08
}
print userConstraints["test"] # Appears ok here
print str(userConstraints) # Has extra DPs here. Why? How to fix?
Output:
0.8
{'test': 0.080000000000000002}
Serialisation logic (on the other side)
obj=ast.literal_eval(theSerialisedString)
Output of serialised obj
{'test': 0.080000000000000002}
0.08
is a computed value, might produce that output. Python 2'sfloat.__str__
truncates values more aggressively thatfloat.__repr__
, and printing a container uses therepr
of the container's contents.repr
discrepancies - IronPython has a completely different implementation of most of the language core. (The standard implementation should show the samefloat.__repr__
output in all 2.7 releases. The Python 3.1float.__repr__
behavior was backported in 2.7.0.)