diff --git a/src/humanize/number.py b/src/humanize/number.py index 52a5356a..b95e2420 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -173,9 +173,16 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str: Returns: str: String containing commas every three digits. + + Raises: + ValueError: If `ndigits` is negative. """ import math + if ndigits is not None and ndigits < 0: + msg = f"ndigits must be >= 0, got {ndigits}" + raise ValueError(msg) + thousands_sep = thousands_separator() decimal_sep = decimal_separator() try: diff --git a/tests/test_number.py b/tests/test_number.py index 5fb12fa6..41a6bcb8 100644 --- a/tests/test_number.py +++ b/tests/test_number.py @@ -83,6 +83,12 @@ def test_intcomma( assert humanize.intcomma(*test_args) == expected +@pytest.mark.parametrize("value", [12345.111, 12345, "12345.111", None]) +def test_intcomma_negative_ndigits(value: float | str | None) -> None: + with pytest.raises(ValueError, match="ndigits must be >= 0"): + humanize.intcomma(value, -1) + + @pytest.mark.parametrize("sign", [1, -1]) def test_intcomma_large_integer(sign: int) -> None: value = sign * (10**400 + 123)