From 7325349f2e87831951decf9cf86b91c41f1d6a47 Mon Sep 17 00:00:00 2001 From: Guillaume Marty Date: Sat, 5 Dec 2026 09:12:29 +0100 Subject: [PATCH] Fix metric() with precision=0 on very large and very small numbers metric() falls back to scientific() outside of the SI prefix range and passes it precision - 1. With precision=0 this is -1, which scientific() turns into an invalid format specifier, so metric(1e50, precision=0) raised ValueError while metric(1500, precision=0) returned '2 k'. Keep the precision of the fallback at 0 or more. Signed-off-by: Guillaume Marty --- src/humanize/number.py | 2 +- tests/test_number.py | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/humanize/number.py b/src/humanize/number.py index e5a2612d..c3259ab7 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -587,7 +587,7 @@ def metric(value: float, unit: str = "", precision: int = 3) -> str: exponent = math.floor(math.log10(abs(value))) if value != 0 else 0 if exponent >= 33 or exponent < -30: - return scientific(value, precision - 1) + unit + return scientific(value, max(precision - 1, 0)) + unit old_bucket = exponent // 3 * 3 value /= 10**old_bucket diff --git a/tests/test_number.py b/tests/test_number.py index 5fb12fa6..f5732f8b 100644 --- a/tests/test_number.py +++ b/tests/test_number.py @@ -334,6 +334,8 @@ def test_clamp(test_args: list[typing.Any], expected: str) -> None: ([2.596e32, "F"], "260 QF"), ([1e50], "1.00 x 10⁵⁰"), ([1e-50], "1.00 x 10⁻⁵⁰"), + ([1e50, "", 0], "1 x 10⁵⁰"), + ([1e-50, "", 0], "1 x 10⁻⁵⁰"), ([-1500, "V"], "-1.50 kV"), ([0.12], "120 m"), ([0.012], "12.0 m"),