From b11b8be11e45cf59e9886f14f58ee30607f2f2bf Mon Sep 17 00:00:00 2001 From: Tyler Goodlet Date: Thu, 26 Aug 2021 08:58:23 -0400 Subject: [PATCH] Use consistent digits throughout `humanize()` --- piker/calc.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/piker/calc.py b/piker/calc.py index 2e64c684..0f6d0e72 100644 --- a/piker/calc.py +++ b/piker/calc.py @@ -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):