# -*- coding: utf-8 -*- """金额精度工具 — 人民币(CNY)统一使用 Decimal + ROUND_HALF_UP。 业务约定:所有金额字段保留 2 位小数(分),与数据库 numeric(*, 2) 对齐。 """ from decimal import Decimal, ROUND_HALF_UP CNY_SCALE = 2 _QUANT = Decimal("0." + "0" * CNY_SCALE) def round_cny(amount: Decimal) -> Decimal: """人民币金额四舍五入到分。""" return amount.quantize(_QUANT, rounding=ROUND_HALF_UP) def to_cny(value) -> Decimal: """将任意数值转为 Decimal 并四舍五入到分。 接受 int / float / str / Decimal; 不可解析时抛出 decimal.InvalidOperation。 """ return round_cny(Decimal(str(value)))