Skip to content

Commit 747706f

Browse files
committed
Clarify intcomma errors for negative precision
1 parent 785e5dc commit 747706f

2 files changed

Lines changed: 15 additions & 1 deletion

File tree

‎src/humanize/number.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,10 +169,14 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
169169
170170
Args:
171171
value (int, float, str): Integer or float to convert.
172-
ndigits (int, None): Digits of precision for rounding after the decimal point.
172+
ndigits (int, None): Non-negative digits of precision for rounding after the
173+
decimal point.
173174
174175
Returns:
175176
str: String containing commas every three digits.
177+
178+
Raises:
179+
ValueError: If a negative precision is used to format a number.
176180
"""
177181
import math
178182

@@ -195,6 +199,9 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
195199
return str(value)
196200

197201
if ndigits is not None:
202+
if ndigits < 0:
203+
msg = "ndigits must be non-negative"
204+
raise ValueError(msg)
198205
result = f"{value:,.{ndigits}f}"
199206
else:
200207
result = f"{value:,}"

‎tests/test_number.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,13 @@ def test_intcomma(
8383
assert humanize.intcomma(*test_args) == expected
8484

8585

86+
@pytest.mark.parametrize("value", [12345, 12345.111, "12345.111"])
87+
@pytest.mark.parametrize("ndigits", [-1, -10])
88+
def test_intcomma_negative_ndigits(value: float | str, ndigits: int) -> None:
89+
with pytest.raises(ValueError, match="^ndigits must be non-negative$"):
90+
humanize.intcomma(value, ndigits=ndigits)
91+
92+
8693
@pytest.mark.parametrize("sign", [1, -1])
8794
def test_intcomma_large_integer(sign: int) -> None:
8895
value = sign * (10**400 + 123)

0 commit comments

Comments
 (0)