Asked By – Manuel Ceron
I am using the standard json module in python 2.6 to serialize a list of floats. However, I’m getting results like this:
>>> import json >>> json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]'
I want the floats to be formated with only two decimal digits. The output should look like this:
>>> json.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]'
I have tried defining my own JSON Encoder class:
class MyEncoder(json.JSONEncoder): def encode(self, obj): if isinstance(obj, float): return format(obj, '.2f') return json.JSONEncoder.encode(self, obj)
This works for a sole float object:
>>> json.dumps(23.67, cls=MyEncoder) '23.67'
But fails for nested objects:
>>> json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]'
I don’t want to have external dependencies, so I prefer to stick with the standard json module.
How can I achieve this?
Now we will see solution for issue: Format floats with standard json module
Note: This does not work in any recent version of Python.
Unfortunately, I believe you have to do this by monkey-patching (which, to my opinion, indicates a design defect in the standard library
json package). E.g., this code:
import json from json import encoder encoder.FLOAT_REPR = lambda o: format(o, '.2f') print(json.dumps(23.67)) print(json.dumps([23.67, 23.97, 23.87]))
23.67 [23.67, 23.97, 23.87]
as you desire. Obviously, there should be an architected way to override
FLOAT_REPR so that EVERY representation of a float is under your control if you wish it to be; but unfortunately that’s not how the
json package was designed.
This question is answered By – Alex Martelli
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0