Sometimes you need to use floating point numbers in JSON, such as price, coordinates, and other information. But the floating point number in python is quite inaccurate, such as the following code:
Copy codeThe Code is as follows:
#! /Usr/bin/env python
Import json as json
Data = [0.333, 0.999, 0.1]
Print json. dumps (data)
The output result is as follows:
Copy codeThe Code is as follows:
$ Python floatjson. py
[0.33300000000000002, 0.999, 0.10000000000000001]
Can I specify the output format of a floating point number, for example, to the last two digits of the decimal point? There is a simple method, although compared with dirty:
Copy codeThe Code is 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)
The output result is as follows:
Copy codeThe Code is as follows:
$ Python floatjson. py
[0.333, 0.999, 0.100]