当前位置:主页 > 软件编程 > Python代码 >

python中精确输出JSON浮点数的方法

时间:2021-02-09 14:35:20 | 栏目:Python代码 | 点击:

有时需要在JSON中使用浮点数,比如价格、坐标等信息。但python中的浮点数相当不准确, 例如下面的代码:

复制代码 代码如下:

#!/usr/bin/env python

import json as json

data = [ 0.333, 0.999, 0.1 ]
print json.dumps(data)


输出结果如下:
复制代码 代码如下:

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

能不能指定浮点数的输出格式,比如精确到小数点后两位呢?有个简单的方法,虽然比较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)


这样输出结果为:
复制代码 代码如下:

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

您可能感兴趣的文章:

相关文章