Format floats with standard json module

StackOverflow

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?





Tutorials