didier/didier/utils/discord/converters/numbers.py

49 lines
1.1 KiB
Python
Raw Normal View History

2022-07-01 12:43:41 +02:00
import math
2022-07-03 18:35:30 +02:00
from typing import Optional, Union
2022-07-01 12:43:41 +02:00
2022-07-01 14:05:00 +02:00
__all__ = ["abbreviated_number"]
2022-07-03 18:35:30 +02:00
def abbreviated_number(argument: str) -> Union[str, int]:
2022-07-01 12:43:41 +02:00
"""Custom converter to allow numbers to be abbreviated
Examples:
515k
4m
"""
if not argument:
raise ValueError
2022-07-03 19:26:30 +02:00
if argument.lower() == "all":
return "all"
2022-07-01 12:43:41 +02:00
if argument.isdecimal():
return int(argument)
units = {"k": 3, "m": 6, "b": 9, "t": 12}
# Get the unit if there is one, then chop it off
2022-07-01 14:05:00 +02:00
value: Optional[int] = None
2022-07-01 12:43:41 +02:00
if not argument[-1].isdigit():
if argument[-1].lower() not in units:
raise ValueError
unit = argument[-1].lower()
2022-07-01 14:05:00 +02:00
value = units.get(unit)
2022-07-01 12:43:41 +02:00
argument = argument[:-1]
2022-07-11 22:23:38 +02:00
# [int][unit] # noqa: E800
2022-07-01 14:05:00 +02:00
if "." not in argument and value is not None:
return int(argument) * (10**value)
2022-07-01 12:43:41 +02:00
2022-07-11 22:23:38 +02:00
# [float][unit] # noqa: E800
2022-07-01 12:43:41 +02:00
if "." in argument:
# Floats themselves are not supported
2022-07-01 14:05:00 +02:00
if value is None:
2022-07-01 12:43:41 +02:00
raise ValueError
as_float = float(argument)
2022-07-01 14:05:00 +02:00
return math.floor(as_float * (10**value))
2022-07-01 12:43:41 +02:00
# Unparseable
raise ValueError