Byte Size Formatter Function

  • Share this:

Code introduction


This function formats the given byte size into a more readable string format such as bytes, KB, MB, or GB.


Technology Stack : Built-in type checking, mathematical operations, string formatting

Code Type : Function

Code Difficulty : Intermediate


                
                    
def format_bytes(size):
    if not isinstance(size, int) or size < 0:
        return "invalid size"
    if size == 0:
        return "0 bytes"
    if size < 1024:
        return f"{size} bytes"
    elif size < 1024**2:
        return f"{size / 1024:.2f} KB"
    elif size < 1024**3:
        return f"{size / 1024**2:.2f} MB"
    else:
        return f"{size / 1024**3:.2f} GB"