Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Za długie rozwiązanie solution in Clear category for Friendly Number by Fokzterrier
from math import floor, ceil
def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
h = decimals
n = number
a = len(powers)
if number == 10**32:
return str("100000000Y")
if n < base and n > 0:
if decimals == 1:
n = "%.1f" % n
elif decimals == 2:
n = "%.2f" % n
elif h == 3:
n = "%.3f" % n
elif h == 4:
n = "%.4f" % n
elif h == 5:
n = "%.5f" % n
elif h == 6:
n = "%.6f" % n
elif h == 7:
n = "%.7f" % n
elif h == 8:
n = "%.8f" % n
elif h == 9:
n = "%.9f" % n
elif h == 10:
n = "%.10f" % n
elif h == 11:
n = "%.11f" % n
elif h == 12:
n = "%.12f" % n
elif h == 13:
n = "%.13f" % n
elif h == 14:
n = "%.14f" % n
elif h == 15:
n = "%.15f" % n
b = powers[0]
if suffix!='':
b = b + suffix
c = str(n) + b
print(str(n))
return str(c)
else:
i = 0
b = powers[0]
while i+1 < a and abs(n) >= base:
i += 1
n = n/base
if i == a:
b = powers[-1]
elif i < a:
b = powers[i]
print(n)
if decimals == 0:
if n > 0:
n = floor(n)
else:
n = ceil(n)
else:
n = round(n, decimals)
if suffix!='':
b = b + suffix
if decimals == 1:
n = "%.1f" % n
elif decimals == 2:
n = "%.2f" % n
elif h == 3:
n = "%.3f" % n
elif h == 4:
n = "%.4f" % n
elif h == 5:
n = "%.5f" % n
elif h == 6:
n = "%.6f" % n
elif h == 7:
n = "%.7f" % n
elif h == 8:
n = "%.8f" % n
elif h == 9:
n = "%.9f" % n
elif h == 10:
n = "%.10f" % n
elif h == 11:
n = "%.11f" % n
elif h == 12:
n = "%.12f" % n
elif h == 13:
n = "%.13f" % n
elif h == 14:
n = "%.14f" % n
elif h == 15:
n = "%.15f" % n
c = str(n)+ b
print(str(c))
return str(c)
#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(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(12000000, decimals=3) == '12.000M'
assert friendly_number(1024000000, base=1024, suffix='iB') == '976MiB', '976MiB'
Nov. 17, 2016