PCv5/app/utils/filters/humanize.py

27 lines
598 B
Python
Raw Normal View History

2021-04-27 19:33:21 +02:00
from app import app
@app.template_filter('humanize')
def humanize(n:float, sd:int=4, unit:str=''):
"""
Print the number human-readable.
n: number
sd: significant digits
unit: unit
Ex: humanize(12345, 2, "o") 12.34ko
"""
suffixes = ['k', 'M', 'G', 'T', 'P']
suffix = ''
for s in suffixes:
if abs(n) > 10**3:
n /= 10**3
suffix = s
else:
break
formatter = f"{{:.{sd}n}}{{}}{{}}{{}}"
spacer = '' if suffix + unit != '' else ''
return formatter.format(float(n), spacer, suffix, unit)