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
- GreenSnippets
- MIT
- Executed with Python 3.11
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
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.
Related snippets
- JavaScript Tested
Format currency and numbers with Intl
Locale-aware money, percent and compact number formatting using the built-in Intl.NumberFormat.
- PHP Tested
Format bytes as a readable size in PHP
Convert a number of bytes to KB, MB or GB with a chosen precision.
- JavaScript Tested
Format bytes as KB, MB, GB
Convert a byte count into a short human-readable size such as 1.5 MB.
- Python Tested
Token bucket rate limiter
Allow bursts but cap the sustained request rate with a small thread-safe token bucket.

