fix: 微信支付元转分改用 Decimal,修复 2.01 元被收 2 元
This commit is contained in:
30
utils/money.py
Normal file
30
utils/money.py
Normal file
@@ -0,0 +1,30 @@
|
||||
"""金额换算:禁止 float 参与元/分转换(避免 2.01 元变成 200 分)。"""
|
||||
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
||||
|
||||
TWO_PLACES = Decimal('0.01')
|
||||
ONE_FEN = Decimal('1')
|
||||
|
||||
|
||||
def to_decimal(amount) -> Decimal:
|
||||
if amount is None:
|
||||
return Decimal('0')
|
||||
if isinstance(amount, Decimal):
|
||||
return amount
|
||||
try:
|
||||
return Decimal(str(amount))
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
return Decimal('0')
|
||||
|
||||
|
||||
def quantize_yuan(amount) -> Decimal:
|
||||
return to_decimal(amount).quantize(TWO_PLACES, rounding=ROUND_HALF_UP)
|
||||
|
||||
|
||||
def yuan_to_fen(amount) -> int:
|
||||
"""人民币元 → 微信支付整数分(四舍五入到分)。"""
|
||||
fen = quantize_yuan(amount) * 100
|
||||
return int(fen.quantize(ONE_FEN, rounding=ROUND_HALF_UP))
|
||||
|
||||
|
||||
def format_yuan(amount) -> str:
|
||||
return f'{quantize_yuan(amount):.2f}'
|
||||
Reference in New Issue
Block a user