← 中文资源

简体中文版本

parse_float 保留 JSON 小数精度

用 parse_float=Decimal 解析 JSON 数字,对比 float 与 Decimal 的合计,让金额运算保持精确。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

float price: 19.99
float total repr: 139.92999999999998
decimal price: 19.99
decimal total: 139.93
float tax: 1.4992499999999997
decimal tax: 1.49925
types: float Decimal
encoded: {"total": "139.93"}

实现说明

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()