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
13 changes: 11 additions & 2 deletions src/humanize/filesize.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,17 @@ def naturalsize(
# mantissa afterward; rounding can push it up to `base` (e.g. 999999 is
# 999.999 kB, which formats to "1000.0 kB"). When that happens and a larger
# suffix is available, step up one suffix so the result reads "1.0 MB".
if exp < len(suffix) and abs(float(format % (abs_bytes / (base**exp)))) >= base:
exp += 1
if exp < len(suffix):
formatted = format % (abs_bytes / (base**exp))
try:
rounded = float(formatted)
except ValueError:
# Custom formats may include literal text (e.g. "~%.1f").
# Keep the suffix chosen from the byte count in that case.
pass
else:
if abs(rounded) >= base:
exp += 1
space = "" if gnu else " "
ret: str = format % (bytes_ / (base**exp)) + space + _(suffix[exp - 1])
return ret
17 changes: 17 additions & 0 deletions tests/test_filesize.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,23 @@
import humanize


@pytest.mark.parametrize(
"value, binary, gnu, fmt, expected",
[
(3000, False, False, "~%.1f", "~3.0 kB"),
(-3000, False, False, "~%.1f", "~-3.0 kB"),
(3000000, False, False, "%.1f (approx)", "3.0 (approx) MB"),
(3072, True, False, "~%.2f", "~3.00 KiB"),
(3072, False, True, "~%.2f", "~3.00K"),
(3000, False, False, "%.1f%%", "3.0% kB"),
],
)
def test_custom_format_with_literal_text(
value: int, binary: bool, gnu: bool, fmt: str, expected: str
) -> None:
assert humanize.naturalsize(value, binary=binary, gnu=gnu, format=fmt) == expected


@pytest.mark.parametrize(
"test_args, expected",
[
Expand Down