2021-04-14 08:25:47 +00:00
|
|
|
from decimal import Decimal
|
|
|
|
|
2020-03-05 17:57:29 +05:00
|
|
|
from num2words import num2words
|
|
|
|
from num2words import CONVERTER_CLASSES, CONVERTES_TYPES
|
|
|
|
|
|
|
|
|
|
|
|
# Can use params:
|
|
|
|
# ~ number: int, float or validate string
|
|
|
|
# ~ to: num2words.CONVERTER_TYPES
|
|
|
|
# ~ lang: num2words.CONVERTER_CLASSES
|
|
|
|
# ~ currency: num2words.CONVERTER_CLASSES.CURRENCY_FORMS
|
|
|
|
|
|
|
|
|
|
|
|
# Jinja2 Global Method
|
|
|
|
def num2words_(number, **kwargs):
|
2021-05-06 18:53:42 +05:00
|
|
|
if _perform_convert(number):
|
2020-03-05 17:57:29 +05:00
|
|
|
if "lang" not in kwargs:
|
|
|
|
kwargs["lang"] = "ru"
|
|
|
|
if "to" not in kwargs or kwargs["to"] not in CONVERTES_TYPES:
|
|
|
|
kwargs["to"] = "cardinal"
|
|
|
|
return num2words(number, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
# Jinja2 Global Method
|
|
|
|
def num2words_currency(number, **kwargs):
|
2021-05-06 18:53:42 +05:00
|
|
|
if _perform_convert(number):
|
2020-03-05 17:57:29 +05:00
|
|
|
if "lang" not in kwargs:
|
|
|
|
kwargs["lang"] = "ru"
|
|
|
|
if "to" not in kwargs or kwargs["to"] not in CONVERTES_TYPES:
|
|
|
|
kwargs["to"] = "currency"
|
|
|
|
if "currency" not in kwargs:
|
|
|
|
kwargs["currency"] = "RUB"
|
2020-03-11 17:36:14 +05:00
|
|
|
result = num2words(number, **kwargs)
|
|
|
|
total = result.split(",")[0]
|
|
|
|
part_word = result.split()[-1]
|
2021-04-14 08:25:47 +00:00
|
|
|
part_number = Decimal(str(number)) % 1
|
2020-03-11 17:36:14 +05:00
|
|
|
return "{total}, {part_n} {part_w}".format(
|
|
|
|
total=total.capitalize(),
|
|
|
|
part_n="{:02d}".format(int(part_number * 100)),
|
|
|
|
part_w=part_word,
|
|
|
|
)
|
2020-03-05 17:57:29 +05:00
|
|
|
|
|
|
|
|
2021-05-06 18:53:42 +05:00
|
|
|
def _perform_convert(number):
|
2020-03-05 17:57:29 +05:00
|
|
|
if isinstance(number, int) or isinstance(number, float):
|
|
|
|
return True
|
|
|
|
if isinstance(number, str):
|
|
|
|
try:
|
|
|
|
number = float(number)
|
|
|
|
return True
|
|
|
|
except ValueError:
|
|
|
|
return False
|
|
|
|
return False
|