Python:在 json 中强制精度 float ?

标签 python json

(更新)

这是我遇到的实际问题。请注意, round() 似乎并没有起到作用。

这是我的代码:

t0=time.time()
# stuff
t1=time.time()
perfdat={'et1' : round(t1-t0,6), 'et2': '%.6f'%(t1-t0)}

以及dict和json分别输出:

{'et2': '0.010214', 'et1': 0.010214000000000001}

{"et2":"0.010214","et1":0.010214000000000001}

(结束更新)

我有一个浮点值,它有很多我不需要的额外精度数字。有没有办法在格式化 json 字符串时截断这些数字?

如果我将值格式化为字符串,我可以获得所需的截断,但我想将值作为(截断的)数字传输。

import json
v=2.030000002

json.dumps({'x':v})     # would like to just have 2.030
'{"x": 2.030000002}'

s= '%.3f' % (v)         # like this, but not as a string
json.dumps({'x' : s})
'{"x": "2.030"}'

最佳答案

将数字包装成一个float:

>>> s = float('%.3f' % (v))
>>> json.dumps({'x' : s})
{"x": 2.03}

关于Python:在 json 中强制精度 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32145824/

相关文章:

python - blender 导入/导出脚本

python - 缩放或平移时 X 轴刻度不会更新

javascript - 使用 Node.js 将对象添加到 JSON

json - GroupByWithSumPipe 对列表进行排序并对分组项的属性求和 Angular

c# - EF6 : How to avoid circular reference?

python - 矩阵处理的 RAM 要求

python - 将列表转换为 Pandas 时间序列

python - Pandas -将列旋转成(条件)聚合字符串

json - 带有JSON.Net的WCF RESTful Web服务:避免双重序列化

javascript - 用 JS 减少 JSON