PCv5/app/utils/filters/humanize.py

27 lines
598 B
Python
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)