Add `puterize()`
parent
da8bccf788
commit
d3d7f8a6f8
|
@ -20,10 +20,17 @@ Handy financial calculations.
|
||||||
import math
|
import math
|
||||||
import itertools
|
import itertools
|
||||||
|
|
||||||
|
from bidict import bidict
|
||||||
|
|
||||||
|
|
||||||
|
_mag2suffix = bidict({3: 'k', 6: 'M', 9: 'B'})
|
||||||
|
|
||||||
|
|
||||||
def humanize(
|
def humanize(
|
||||||
|
|
||||||
number: float,
|
number: float,
|
||||||
digits: int = 1
|
digits: int = 1
|
||||||
|
|
||||||
) -> str:
|
) -> str:
|
||||||
'''Convert large numbers to something with at most ``digits`` and
|
'''Convert large numbers to something with at most ``digits`` and
|
||||||
a letter suffix (eg. k: thousand, M: million, B: billion).
|
a letter suffix (eg. k: thousand, M: million, B: billion).
|
||||||
|
@ -36,19 +43,38 @@ def humanize(
|
||||||
if not number or number <= 0:
|
if not number or number <= 0:
|
||||||
return round(number, ndigits=digits)
|
return round(number, ndigits=digits)
|
||||||
|
|
||||||
mag2suffix = {3: 'k', 6: 'M', 9: 'B'}
|
|
||||||
mag = math.floor(math.log(number, 10))
|
mag = math.floor(math.log(number, 10))
|
||||||
if mag < 3:
|
if mag < 3:
|
||||||
return round(number, ndigits=digits)
|
return round(number, ndigits=digits)
|
||||||
|
|
||||||
maxmag = max(itertools.takewhile(lambda key: mag >= key, mag2suffix))
|
maxmag = max(itertools.takewhile(lambda key: mag >= key, _mag2suffix))
|
||||||
|
|
||||||
return "{value}{suffix}".format(
|
return "{value}{suffix}".format(
|
||||||
value=round(number/10**maxmag, ndigits=digits),
|
value=round(number/10**maxmag, ndigits=digits),
|
||||||
suffix=mag2suffix[maxmag],
|
suffix=_mag2suffix[maxmag],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def puterize(
|
||||||
|
|
||||||
|
text: str,
|
||||||
|
digits: int = 1,
|
||||||
|
|
||||||
|
) -> float:
|
||||||
|
'''Inverse of ``humanize()`` above.
|
||||||
|
|
||||||
|
'''
|
||||||
|
try:
|
||||||
|
suffix = str(text)[-1]
|
||||||
|
mult = _mag2suffix.inverse[suffix]
|
||||||
|
value = text.rstrip(suffix)
|
||||||
|
return round(float(value) * 10**mult, ndigits=digits)
|
||||||
|
|
||||||
|
except KeyError:
|
||||||
|
# no matching suffix try just the value
|
||||||
|
return float(text)
|
||||||
|
|
||||||
|
|
||||||
def pnl(
|
def pnl(
|
||||||
|
|
||||||
init: float,
|
init: float,
|
||||||
|
|
Loading…
Reference in New Issue