From e5a3976c5a053ae681ec388308d95065e4e35498 Mon Sep 17 00:00:00 2001 From: e-nikolov Date: Mon, 4 Dec 2023 00:37:57 +0100 Subject: [PATCH] metric: fix precision format --- src/humanize/number.py | 2 +- tests/test_number.py | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/humanize/number.py b/src/humanize/number.py index 9329c28..034144a 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -562,7 +562,7 @@ def metric(value: float, unit: str = "", precision: int = 3) -> str: ordinal_ = "mμnpfazyrq"[(-exponent - 1) // 3] else: ordinal_ = "" - value_ = format(value, ".%if" % (precision - (exponent % 3) - 1)) + value_ = format(value, ".%if" % max(0, precision - (exponent % 3) - 1)) if not (unit or ordinal_) or unit in ("°", "′", "″"): space = "" else: diff --git a/tests/test_number.py b/tests/test_number.py index 9bb9475..00d9a9c 100644 --- a/tests/test_number.py +++ b/tests/test_number.py @@ -269,6 +269,27 @@ def test_clamp(test_args: list[typing.Any], expected: str) -> None: ([0.1, "°"], "100m°"), ([100], "100"), ([0.1], "100 m"), + ([1.5123, "", 0], "2"), + ([10.5123, "", 0], "11"), + ([10.5123, "", 1], "11"), + ([10.5123, "", 2], "11"), + ([10.5123, "", 3], "10.5"), + ([1, "", 0], "1"), + ([10, "", 0], "10"), + ([100, "", 0], "100"), + ([1000, "", 0], "1 k"), + ([1, "", 1], "1"), + ([10, "", 1], "10"), + ([100, "", 1], "100"), + ([1000, "", 1], "1 k"), + ([1, "", 2], "1.0"), + ([10, "", 2], "10"), + ([100, "", 2], "100"), + ([1000, "", 2], "1.0 k"), + ([1, "", 3], "1.00"), + ([10, "", 3], "10.0"), + ([100, "", 3], "100"), + ([1000, "", 3], "1.00 k"), ([math.nan], "NaN"), ([math.nan, "m"], "NaN"), ([math.inf], "+Inf"),