filters: add humanize filter

This commit is contained in:
Darks 2021-04-27 19:33:21 +02:00
parent 4be0e1572c
commit 9afdc63a8e
Signed by untrusted user: Darks
GPG Key ID: 7515644268BE1433
2 changed files with 27 additions and 1 deletions

View File

@ -1,3 +1,3 @@
# Register filters here
from app.utils.filters import date, is_title, markdown, pluralize
from app.utils.filters import date, humanize, is_title, markdown, pluralize

View File

@ -0,0 +1,26 @@
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)