I am trying to write an application to convert bytes to kb to mb to gb to tb. Here\'s what I have so far:
def size_format(b):
if b < 1000:
r
I have improved, in my opininion, @whereisalext answer to have a somewhat more generic function which does not require one to add more if statements once more units are going to be added:
AVAILABLE_UNITS = ['bytes', 'KB', 'MB', 'GB', 'TB']
def get_amount_and_unit(byte_amount):
for index, unit in enumerate(AVAILABLE_UNITS):
lower_threshold = 0 if index == 0 else 1024 ** (index - 1)
upper_threshold = 1024 ** index
if lower_threshold <= byte_amount < upper_threshold:
if lower_threshold == 0:
return byte_amount, unit
else:
return byte_amount / lower_threshold, AVAILABLE_UNITS[index - 1]
# Default to the maximum
max_index = len(AVAILABLE_UNITS) - 1
return byte_amount / (1024 ** max_index), AVAILABLE_UNITS[max_index]
Do note that this differs slightly frrom @whereisalext's algo: