Files
WeechatPayBot/bot/utils/amount_parser.py

35 lines
1001 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.
from decimal import Decimal, InvalidOperation
import re
def parse_rub_amount(raw_value: str) -> Decimal | None:
normalized_value = raw_value.lower().strip().replace(",", ".")
normalized_value = normalized_value.replace(" ", "")
normalized_value = re.sub(r"руб(лей|ля|ль|ле|\.?)", "", normalized_value)
normalized_value = re.sub(r"[^\d.]", "", normalized_value)
if not normalized_value or normalized_value.count(".") > 1:
return None
try:
amount = Decimal(normalized_value)
except InvalidOperation:
return None
if amount <= 0:
return None
if amount.as_tuple().exponent < -2:
return None
return amount.quantize(Decimal("0.01"))
def format_rub_amount(amount: Decimal) -> str:
normalized_amount = amount.quantize(Decimal("0.01"))
if normalized_amount == normalized_amount.to_integral():
return f"{int(normalized_amount)}"
return f"{normalized_amount:.2f}".replace(".", ",")