"""金额与比率的定点运算。积分只向下取整,避免四舍五入把释放总额做超。""" from __future__ import annotations from decimal import Decimal, ROUND_DOWN QUANT = Decimal("0.00000001") def to_decimal(value: object) -> Decimal: if isinstance(value, Decimal): return value return Decimal(str(value)) def money(value: object) -> Decimal: return to_decimal(value).quantize(QUANT, rounding=ROUND_DOWN) def rate(value: object) -> Decimal: number = to_decimal(value) if number < 0: number = Decimal("0") elif number > 1: number = Decimal("1") return number.quantize(QUANT, rounding=ROUND_DOWN) def ratio(numerator: int, denominator: int) -> Decimal: if denominator <= 0: return Decimal("0") return rate(Decimal(numerator) / Decimal(denominator))