Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Friendly Number by tmaki
def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
count = 0
originalNumber = number
number = abs(number)
if number >= base: #if the number is greater than the base
while number >= base: #increase count and divide by the base until the number is less than the base
if count < len(powers)-1:
count += 1
else:
break
number /= base
number = abs(originalNumber)/(base**count)
if decimals:
splitNum = str(float(round(number,decimals))).split(".")
answer = splitNum[0] + "." + splitNum[1][0:decimals].ljust(decimals,"0") + powers[count] + suffix
else:
splitNum = str(float(number)).split(".")
answer = splitNum[0] + powers[count] + suffix
else:
if decimals:
answer = str(float(number)).ljust(len(str(number))+decimals+1,"0") + powers[count]+ suffix
else:
answer = str(number) + powers[count] + suffix
if originalNumber >= 0:
return answer
else:
return "-" + answer
#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. 13, 2016
Comments: