如何使用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,但遗憾的是没有预期的结果。
浮动不是为了保存那种信息而设计的。 0.020和0.02是相同的。
但是,您可以手动设置小数位数:
import json
test = 0.020
print(json.dumps({'test': '{:.3f}'.format(test)}))
将打印
{"test": "0.020"}
请注意a)现在这是一个字符串,不再是浮点数,而b){:.3f}
部分专门将小数位数设置为3。
最后我被迫使用非标准的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
库的方法,但至少它正在工作。