"""金额换算：禁止 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}'
