first commit
This commit is contained in:
34
bot/utils/amount_parser.py
Normal file
34
bot/utils/amount_parser.py
Normal file
@@ -0,0 +1,34 @@
|
||||
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(".", ",")
|
||||
Reference in New Issue
Block a user