Sometimes you need to use floating-point numbers in JSON, such as price, coordinates, and so on. But the floating-point numbers in Python are rather inaccurate, such as the following code:
Copy Code code as follows:
#!/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:
Copy Code code as follows:
$ python floatjson.py
[0.33300000000000002, 0.999, 0.10000000000000001]
Can you specify the output format for floating-point numbers, such as two digits after the decimal point? There is a simple method, although the comparison dirty:
Copy Code code as follows:
#!/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)
This results in the following output:
Copy Code code as follows:
$ python floatjson.py
[0.333, 0.999, 0.100]