Skip to content

Commit 43d6dc6

Browse files
authored
metric: Fix precision format (#159)
2 parents 5cb0323 + e5a3976 commit 43d6dc6

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/humanize/number.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -562,7 +562,7 @@ def metric(value: float, unit: str = "", precision: int = 3) -> str:
562562
ordinal_ = "mμnpfazyrq"[(-exponent - 1) // 3]
563563
else:
564564
ordinal_ = ""
565-
value_ = format(value, ".%if" % (precision - (exponent % 3) - 1))
565+
value_ = format(value, ".%if" % max(0, precision - (exponent % 3) - 1))
566566
if not (unit or ordinal_) or unit in ("°", "′", "″"):
567567
space = ""
568568
else:

tests/test_number.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,27 @@ def test_clamp(test_args: list[typing.Any], expected: str) -> None:
269269
([0.1, "°"], "100m°"),
270270
([100], "100"),
271271
([0.1], "100 m"),
272+
([1.5123, "", 0], "2"),
273+
([10.5123, "", 0], "11"),
274+
([10.5123, "", 1], "11"),
275+
([10.5123, "", 2], "11"),
276+
([10.5123, "", 3], "10.5"),
277+
([1, "", 0], "1"),
278+
([10, "", 0], "10"),
279+
([100, "", 0], "100"),
280+
([1000, "", 0], "1 k"),
281+
([1, "", 1], "1"),
282+
([10, "", 1], "10"),
283+
([100, "", 1], "100"),
284+
([1000, "", 1], "1 k"),
285+
([1, "", 2], "1.0"),
286+
([10, "", 2], "10"),
287+
([100, "", 2], "100"),
288+
([1000, "", 2], "1.0 k"),
289+
([1, "", 3], "1.00"),
290+
([10, "", 3], "10.0"),
291+
([100, "", 3], "100"),
292+
([1000, "", 3], "1.00 k"),
272293
([math.nan], "NaN"),
273294
([math.nan, "m"], "NaN"),
274295
([math.inf], "+Inf"),

0 commit comments

Comments
 (0)