From fc76fd3764026c939ea5742b4843e1832a8978ed Mon Sep 17 00:00:00 2001 From: Xingrui <884633441@qq.com> Date: Mon, 12 Oct 2026 21:49:54 +0800 Subject: [PATCH] Preserve invalid string inputs in intcomma --- src/humanize/number.py | 12 ++++++------ tests/test_i18n.py | 20 ++++++++++++++++++++ tests/test_number.py | 6 ++++++ 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/humanize/number.py b/src/humanize/number.py index 52a5356a..0972ac9c 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -180,13 +180,13 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str: decimal_sep = decimal_separator() try: if isinstance(value, str): - value = value.replace(thousands_sep, "").replace(decimal_sep, ".") - if not math.isfinite(float(value)): - return _format_not_finite(float(value)) - if "." in value: - value = float(value) + normalized = value.replace(thousands_sep, "").replace(decimal_sep, ".") + if not math.isfinite(float(normalized)): + return _format_not_finite(float(normalized)) + if "." in normalized: + value = float(normalized) else: - value = int(value) + value = int(normalized) elif not isinstance(value, int): if not math.isfinite(float(value)): return _format_not_finite(float(value)) diff --git a/tests/test_i18n.py b/tests/test_i18n.py index 683fe3ce..47f8c59e 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -132,6 +132,26 @@ def test_intcomma() -> None: assert humanize.intcomma(number) == "10,000,000" +@pytest.mark.parametrize( + "locale, value", + [ + ("de_DE", "kein, Betrag."), + ("de_DE", "1.234,5oops"), + ("fr_FR", "pas un nombre, vraiment"), + ("fr_FR", "1 234,5oops"), + ], +) +@pytest.mark.parametrize("ndigits", [None, 0, 2]) +def test_intcomma_invalid_string(locale: str, value: str, ndigits: int | None) -> None: + try: + humanize.activate(locale) + assert humanize.intcomma(value, ndigits) == value + except FileNotFoundError: + pytest.skip("Generate .mo with scripts/generate-translation-binaries.sh") + finally: + humanize.deactivate() + + def test_naturaldelta() -> None: seconds = 1234 * 365 * 24 * 60 * 60 diff --git a/tests/test_number.py b/tests/test_number.py index 5fb12fa6..fc269e1b 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", ["hello, world", "1,234oops", "1,234e3", "1,2.3.4"]) +@pytest.mark.parametrize("ndigits", [None, 0, 2]) +def test_intcomma_invalid_string(value: str, ndigits: int | None) -> None: + assert humanize.intcomma(value, ndigits) == value + + @pytest.mark.parametrize("sign", [1, -1]) def test_intcomma_large_integer(sign: int) -> None: value = sign * (10**400 + 123)