Use consistent digits throughout `humanize()`
parent
5b923ae577
commit
b11b8be11e
|
@ -22,22 +22,28 @@ import itertools
|
|||
|
||||
|
||||
def humanize(number, digits=1):
|
||||
"""Convert large numbers to something with at most 3 digits and
|
||||
'''Convert large numbers to something with at most ``digits`` and
|
||||
a letter suffix (eg. k: thousand, M: million, B: billion).
|
||||
"""
|
||||
|
||||
'''
|
||||
try:
|
||||
float(number)
|
||||
except ValueError:
|
||||
return 0
|
||||
if not number or number <= 0:
|
||||
return number
|
||||
return round(number, ndigits=digits)
|
||||
|
||||
mag2suffix = {3: 'k', 6: 'M', 9: 'B'}
|
||||
mag = math.floor(math.log(number, 10))
|
||||
if mag < 3:
|
||||
return number
|
||||
return round(number, ndigits=digits)
|
||||
|
||||
maxmag = max(itertools.takewhile(lambda key: mag >= key, mag2suffix))
|
||||
return "{:.{digits}f}{}".format(
|
||||
number/10**maxmag, mag2suffix[maxmag], digits=digits)
|
||||
|
||||
return "{value}{suffix}".format(
|
||||
value=round(number/10**maxmag, ndigits=digits),
|
||||
suffix=mag2suffix[maxmag],
|
||||
)
|
||||
|
||||
|
||||
def percent_change(init, new):
|
||||
|
|
Loading…
Reference in New Issue