实现说明
parse_float 保留 JSON 小数精度以函数 main为骨架。
使用要点
- 跑完文件,输出里会留下标记——
float price:、float total repr:、decimal price:。
常见问题
运行「parse_float 保留 JSON 小数精度」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 float price:、float total repr:、decimal price: 标签标明各步骤。
代码示例
import json
from decimal import Decimal
PAYLOAD = '{"price": 19.99, "quantity": 7, "tax_rate": 0.075}'
def main() -> None:
default = json.loads(PAYLOAD)
exact = json.loads(PAYLOAD, parse_float=Decimal)
print('float price:', default['price'])
print('float total repr:', repr(default['price'] * default['quantity']))
print('decimal price:', exact['price'])
print('decimal total:', exact['price'] * exact['quantity'])
print('float tax:', default['price'] * default['tax_rate'])
print('decimal tax:', exact['price'] * exact['tax_rate'])
print('types:', type(default['price']).__name__, type(exact['price']).__name__)
encoded = json.dumps({'total': str(exact['price'] * exact['quantity'])})
print('encoded:', encoded)
if __name__ == '__main__':
main()