Skip to content
Open
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
7 changes: 6 additions & 1 deletion src/human_readable/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,5 +61,10 @@ def file_size(
for i, suffix in enumerate(suffixes):
unit = base ** (i + 2)
if byte_size < unit:
return f"{base * byte_size / unit:{formatting}}{suffix}"
formatted = f"{base * byte_size / unit:{formatting}}"
# Rounding can push the mantissa to base (e.g. 999,999 bytes is
# 999.999 KB, which rounds to "1000.0 KB"). Step up one suffix.
if float(formatted) >= base and i + 1 < len(suffixes):
return f"{byte_size / unit:{formatting}}{suffixes[i + 1]}"
return f"{formatted}{suffix}"
return f"{base * byte_size / unit:{formatting}}{suffix}"
4 changes: 4 additions & 0 deletions tests/unit/test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
(2900000, "2.9 MB"), # millions number
(2000000000, "2.0 GB"), # billions number
(10**26 * 30, "3000.0 YB"), # giant number
# Rollover: mantissa rounds up to base, must carry to the next suffix
(999999, "1.0 MB"),
(999999999, "1.0 GB"),
(999999999999, "1.0 TB"),
],
)
def test_file_size(params: int, expected: str) -> None:
Expand Down