带有前导零的python json浮点数

问题描述 投票:2回答:2

如何使用python(3.5)json标准库打印带有尾随零的浮点数?

import json
to_be_serialized = {'something': 0.020}
print(json.dumps(to_be_serialized))
{"something": 0.02}  # desired output: {"something": 0.020}

我尝试了this,但遗憾的是没有预期的结果。

python json python-3.x
2个回答
1
投票

浮动不是为了保存那种信息而设计的。 0.020和0.02是相同的。

但是,您可以手动设置小数位数:

import json
test = 0.020
print(json.dumps({'test': '{:.3f}'.format(test)}))

将打印

{"test": "0.020"}

请注意a)现在这是一个字符串,不再是浮点数,而b){:.3f}部分专门将小数位数设置为3。


1
投票

最后我被迫使用非标准的python库simplejson。 (因为json包不支持小数)

import simplejson as json
from decimal import Decimal

to_be_serialized = {'something': Decimal('0.020').quantize(Decimal('.0001'))}
print(json.dumps(to_be_serialized))

我无法找到使用标准json库的方法,但至少它正在工作。

© www.soinside.com 2019 - 2024. All rights reserved.