You can download this code by clicking the button below.
This code is now available for download.
This function returns the appropriate unit (B, KB, MB, GB, TB) based on the size of the bytes passed to it.
Technology Stack : Built-in functions
Code Type : Function
Code Difficulty : Intermediate
def format_bytes(size):
if size < 1024:
return f"{size} B"
elif size < 1024**2:
return f"{size / 1024:.2f} KB"
elif size < 1024**3:
return f"{size / 1024**2:.2f} MB"
elif size < 1024**4:
return f"{size / 1024**3:.2f} GB"
else:
return f"{size / 1024**4:.2f} TB"