Heim  >  Artikel  >  Backend-Entwicklung  >  python中精确输出JSON浮点数的方法

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

WBOY
WBOYOriginal
2016-06-16 08:44:291236Durchsuche

有时需要在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]
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn