python处理JSON中的浮点数不精确问题,pythonjson浮点数,有时需要在JSON中使用
python处理JSON中的浮点数不精确问题,pythonjson浮点数,有时需要在JSON中使用
有时需要在JSON中使用浮点数,比如价格、坐标等信息。但python中的浮点数相当不准确, 例如下面的代码:
#!/usr/bin/env pythonimport json as jsondata = [ 0.333, 0.999, 0.1 ]print json.dumps(data)
输出结果如下:
$ python floatjson.py[0.33300000000000002, 0.999, 0.10000000000000001]
能不能指定浮点数的输出格式,比如精确到小数点后两位呢?有个简单的方法,虽然比较dirty:
#!/usr/bin/env pythonimport jsonjson.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]
相关内容
- python 缩略图,给图片加水印,,这里使用了PIL类库。[
- python比较两个文件的差异,python两个差异,下面的pytho
- Python 求解组合问题,python求解组合,[Python]代码de
- Python sqlite模块,pythonsqlite模块,sqlite是非常著名的
- Python删除指定目录下的过期文件,,实现类似该命令的操
- MySQLdb and threading Base Usage,mysqldbthreading,[Python]代码im
- Python 读取纯真IP数据库,pythonip数据库,[Python]代码#!
- Python RSS阅读器,pythonrss阅读器,[Python]代码#
- python字符串填充,python字符串,string1 = "N
- python判断数组是否包含指定的元素的方法,python数组
评论关闭