Bytes to Unit Conversion Function

  • Share this:

Code introduction


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"