Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Friendly Number by Andreas_Strus
def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
number = int(number)
p = 0
for n in range(len(powers)):
b = base**n
if abs(number / b) >= 1:
p = n
number = float(number)
number = number / base**p
numberd = number * 10**decimals
if decimals > 0:
if abs(numberd) - abs(int(numberd)) >= 0.5:
if numberd < 0:
numberd = numberd - 1
else:
numberd = numberd + 1
numberd = int(numberd)
str1 = str(numberd)[0:(len(str(numberd)) - decimals)]
if decimals > 0:
str1 = str1 + "."
str2 = str(numberd)[(len(str(numberd)) - decimals):len(str(numberd))]
number = str1 + str2 + powers[p] + suffix
if numberd == 0 :
number = "0"
if decimals > 0:
number = "0."
for f in range (decimals):
number = number + "0"
number = number + powers[p] + suffix
return str(number)
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
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'
Oct. 21, 2016