Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
let's be friends, number! solution in Clear category for Friendly Number by shobble
import math
from decimal import Decimal
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.
"""
p = 0
number = Decimal(number)
base = Decimal(base)
num_powers = len(powers)
while abs(number) >= base and p < num_powers -1:
number /= base
p += 1
if decimals == 0:
# crappy round-towards-zero
if number < 0:
number = math.ceil(number)
else:
number = math.floor(number)
else:
number = round(number, decimals)
pwr = powers[p]
ret = f'{number:.{decimals}f}{pwr}{suffix}'
#print(ret)
return ret
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert friendly_number(10**32) == '100000000Y'
assert friendly_number(10**24) == '1Y'
friendly_number(255000000000, powers=["","k","M"])
assert friendly_number(102) == '102', '102'
assert friendly_number(10240) == '10k', '10k'
assert friendly_number(12341234, decimals=1) == '12.3M', '12.3M'
assert friendly_number(12461, decimals=1) == '12.5k', '12.5k'
assert friendly_number(1024000000, base=1024, suffix='iB') == '976MiB', '976MiB'
June 2, 2020