Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Fully documented solution in Clear category for Friendly Number by Ylliw
def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
from math import log
sign='-' if number<0 else '' # keep the sign aside
number=abs(number) # let's work with positiv numbers
power=int(log(number,base)) if number>0 else 0 # calculate approching power
if power>=len(powers): power=len(powers)-1 # fix power if bigger than our existing naming
x=number/(base**power) # calcul the float value in front of power
if decimals: # if decimals are requested
s=str(round(x,decimals)) # convert it to string
if '.' in s: # check if there is already a dot
s+='0'*(decimals-len(s)+s.index('.')+1) # pad it with 0s
else: # no decimal requested
s=str(int(x)) # round towards 0
return sign+s+powers[power]+suffix # return the final string
Dec. 7, 2017