Skip to content
GreenSnippets

Format bytes as a human-readable size

Convert a byte count into KB, MB, GB and so on with a configurable number of decimals.

Python
def format_bytes(size, decimals=1):
    units = ["B", "KB", "MB", "GB", "TB", "PB"]
    value = float(abs(size))
    index = 0
    while value >= 1024 and index < len(units) - 1:
        value /= 1024
        index += 1
    text = f"{value:.{decimals}f}".rstrip("0").rstrip(".") if index else str(int(value))
    return f"{'-' if size < 0 else ''}{text} {units[index]}"

Example / expected output

Output
format_bytes(1536)       # '1.5 KB'
format_bytes(5_000_000)  # '4.8 MB'

How it works

Uses base-1024 steps. The loop stops at the largest unit, so absurdly large numbers still format. Negative values keep their sign.