Handle numbers of magnitude 2

kivy_mainline_and_py3.8
Tyler Goodlet 2018-02-13 10:35:11 -05:00
parent e4ff113dfc
commit f31ebe6fcd
1 changed files with 3 additions and 1 deletions

View File

@ -9,10 +9,12 @@ def humanize(number):
"""Convert large numbers to something with at most 3 digits and """Convert large numbers to something with at most 3 digits and
a letter suffix (eg. k: thousand, M: million, B: billion). a letter suffix (eg. k: thousand, M: million, B: billion).
""" """
if number <= 0: if not number or number <= 0:
return number return number
mag2suffix = {3: 'k', 6: 'M', 9: 'B'} mag2suffix = {3: 'k', 6: 'M', 9: 'B'}
mag = math.floor(math.log(number, 10)) mag = math.floor(math.log(number, 10))
if mag < 3:
return number
maxmag = max(itertools.takewhile(lambda key: mag >= key, mag2suffix)) maxmag = max(itertools.takewhile(lambda key: mag >= key, mag2suffix))
return "{:.3f}{}".format(number/10**maxmag, mag2suffix[maxmag]) return "{:.3f}{}".format(number/10**maxmag, mag2suffix[maxmag])