A method in python that outputs exactly a JSON floating point number

  • 2020-04-02 13:37:24
  • OfStack

Sometimes you need to use floating point Numbers in JSON, such as prices, coordinates, and so on. But floating point Numbers in python are rather inaccurate, as shown in the following code:


#!/usr/bin/env python
import json as json
data = [ 0.333, 0.999, 0.1 ]
print json.dumps(data)

The output results are as follows:

$ python floatjson.py
[0.33300000000000002, 0.999, 0.10000000000000001]

Can you specify the format of the floating-point output, say, to two decimal places? Here's an easy way, albeit dirty:

#!/usr/bin/env python
import json
json.encoder.FLOAT_REPR = lambda x: format(x, '.3f')
data = [ 0.333, 0.999, 0.1 ]
print json.dumps(data)

The output result is:

$ python floatjson.py 
[0.333, 0.999, 0.100]


Related articles: