Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Clear and documented solution with operator and f-string solution in Clear category for Friendly Number by bsquare
from operator import truediv, floordiv
def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
# Defines the power.
power = 0
op = floordiv if number >= 10 ** 32 else truediv
while abs(number) >= base and power < len(powers) - 1:
number, power = op(number, base), power + 1
# Hacks the number to have an integer instead of the automatic rounding, which
# does not match the awaited result.
number = number if decimals else int(number)
# Returns the formatted result.
return f"{number:.{decimals}F}{powers[power]}{suffix}"
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert friendly_number(-150, base=100, powers=['', 'd', 'D']) == '-1d', '-150'
assert friendly_number(1000000000000000000000000) == '1Y', '1Y'
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'
assert friendly_number(255000000000, powers=['', 'k', 'M']) == '255000M', '255000000000'
Aug. 3, 2019