27 lines
598 B
Python
27 lines
598 B
Python
|
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.34 ko
|
|||
|
"""
|
|||
|
|
|||
|
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)
|