This question already has an answer here:
- How to set the number of float digits JSONEncoder produces? 3 answers
I am trying to make my JSON encoder dump floats with only 2 decimal precision. So '2.241' becomes '2.24'
I've read in this answer by Alex Martelli that you can overwrite the default FLOAT_REPR of json.encoder. I have tried the following:
>>> import json
>>> json.encoder.FLOAT_REPR = lambda o: format(o, '.2f')
But I dont get the same results:
>>> json.dumps(2.241)
'2.241'
And I can even verify the FLOAT_REPR is changed:
>>> print json.encoder.FLOAT_REPR
<function <lambda> at 0xb....>
And works as expected:
>>> json.encoder.FLOAT_REPR(2.241)
2.24
Why is the built-in JSON module not using the FLOAT_REPR when I can see that it has been overwritten and the solution should be working according to Alex Martelli?
I have tested this on two different computers, both running Python 2.7.6 on Ubuntu 14.0.4.