Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Floats and f-strings solution in Clear category for Friendly Number by kkkkk
from math import trunc
def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
"""Format a number as friendly text, using common suffixes."""
non_decimal_num = float(number)
power_idx = 0
while abs(non_decimal_num) >= base:
non_decimal_num = non_decimal_num / base
power_idx += 1
if power_idx + 1 == len(powers):
break
if decimals:
decimal_str = f'{non_decimal_num:.{decimals}f}'
else:
decimal_str = f'{trunc(non_decimal_num)}'
return f'{decimal_str}{powers[power_idx]}{suffix}'
Dec. 18, 2019