def human_format(num):
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
# add more suffixes if you need them
return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
print('the answer is %s' % human_format(7436313)) # prints 'the answer is 7.44M'
def human_format(num, precision=2, suffixes=['', 'K', 'M', 'G', 'T', 'P']):
m = sum([abs(num/1000.0**x) >= 1 for x in range(1, len(suffixes))])
return f'{num/1000.0**m:.{precision}f}{suffixes[m]}'
print('the answer is %s' % human_format(7454538)) # prints 'the answer is 7.45M'
#make the dictionary to store what to put after the result (ex. 'Billion'). You can go further with this then I did, or to wherever you wish.
#import the desired rounding mechanism. You will not need to do this for round.
from math import floor
magnitudeDict={0:'', 1:'Thousand', 2:'Million', 3:'Billion', 4:'Trillion', 5:'Quadrillion', 6:'Quintillion', 7:'Sextillion', 8:'Septillion', 9:'Octillion', 10:'Nonillion', 11:'Decillion'}
def simplify(num):
num=floor(num)
magnitude=0
while num>=1000.0:
magnitude+=1
num=num/1000.0
return(f'{floor(num*100.0)/100.0} {magnitudeDict[magnitude]}')
# print number in a readable format.
# default is up to 3 decimal digits and can be changed
# works on numbers in the range of 1e-15 to 1e 1e15 include negatives numbers
# can force the number to a specific magnitude unit
def human_format(num:float, force=None, ndigits=3):
perfixes = ('p', 'n', 'u', 'm', '', 'K', 'M', 'G', 'T')
one_index = perfixes.index('')
if force:
if force in perfixes:
index = perfixes.index(force)
magnitude = 3*(index - one_index)
num = num/(10**magnitude)
else:
raise ValueError('force value not supported.')
else:
div_sum = 0
if(abs(num) >= 1000):
while abs(num) >= 1000:
div_sum += 1
num /= 1000
else:
while abs(num) <= 1:
div_sum -= 1
num *= 1000
temp = round(num, ndigits) if ndigits else num
if temp < 1000:
num = temp
else:
num = 1
div_sum += 1
index = one_index + div_sum
return str(num).rstrip('0').rstrip('.') + perfixes[index]