From c18458aaa04cfac2d434b42f51573b4428909f0a Mon Sep 17 00:00:00 2001 From: Manshi Date: Tue, 20 Oct 2026 19:18:57 +0530 Subject: [PATCH] fix: preserve fractional bytes in naturalsize --- src/humanize/filesize.py | 5 ++++- tests/test_filesize.py | 6 ++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/humanize/filesize.py b/src/humanize/filesize.py index 063affe0..15d758bd 100644 --- a/src/humanize/filesize.py +++ b/src/humanize/filesize.py @@ -94,7 +94,10 @@ def naturalsize( return _("%d Byte") % int(bytes_) if abs_bytes < base: - return f"{int(bytes_)}B" if gnu else _("%d Bytes") % int(bytes_) + if bytes_.is_integer(): + return f"{int(bytes_)}B" if gnu else _("%d Bytes") % int(bytes_) + formatted_bytes = format % bytes_ + return f"{formatted_bytes}B" if gnu else f"{formatted_bytes} Bytes" from math import log diff --git a/tests/test_filesize.py b/tests/test_filesize.py index 645751b9..40e5090d 100644 --- a/tests/test_filesize.py +++ b/tests/test_filesize.py @@ -74,10 +74,12 @@ ([3000, False, True, "%.3f"], "2.930K"), ([3000000000, False, True, "%.0f"], "3G"), ([10**26 * 30, True, False, "%.3f"], "2.423 RiB"), - ([1.123456789], "1 Bytes"), + ([1.5], "1.5 Bytes"), + ([1.9], "1.9 Bytes"), ([1.123456789 * 10**3], "1.1 kB"), ([1.123456789 * 10**6], "1.1 MB"), - ([1.123456789, False, True], "1B"), + ([1.5, False, True], "1.5B"), + ([1.9, False, True], "1.9B"), ([1.123456789 * 10**3, False, True], "1.1K"), ([1.123456789 * 10**6, False, True], "1.1M"), # Rounding must not leave the mantissa at the base while a larger suffix