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

WBOY
Release: 2016-06-16 08:44:29
Original
1302 people have browsed it

有时需要在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]
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template