Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/humanize/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

from humanize.bitrate import natural_bitrate
from humanize.filesize import naturalsize
from humanize.i18n import activate, deactivate, decimal_separator, thousands_separator
from humanize.lists import natural_list
Expand Down Expand Up @@ -36,6 +37,7 @@
"intcomma",
"intword",
"metric",
"natural_bitrate",
"natural_list",
"naturaldate",
"naturalday",
Expand Down
23 changes: 23 additions & 0 deletions src/humanize/bitrate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from __future__ import annotations


def natural_bitrate(value: float) -> str:
"""Format a bitrate value (bps) into a human-readable string using SI units (1000-based).

Args:
value: Bitrate in bits per second (bps).

Returns:
Human-readable bitrate string (e.g., "1 kbps", "5.2 Mbps", "10 Gbps").
"""
units = ["bps", "kbps", "Mbps", "Gbps", "Tbps"]
unit_index = 0

while value >= 1000 and unit_index < len(units) - 1:
value /= 1000
unit_index += 1

if unit_index == 0:
return f"{value:.0f} {units[unit_index]}"
else:
return f"{value:.1f} {units[unit_index]}"