Files
Neo-ZQYY/packages/shared/src/neozqyy_shared/money.py

24 lines
704 B
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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)))