From 30ecb2367daa875062532aafa6a49cabf08e7a1a Mon Sep 17 00:00:00 2001 From: ApparentlyTejas Date: Sun, 25 Oct 2026 20:59:47 +0100 Subject: [PATCH] Fix ordinal() suffix for negative integers value % 10 and value % 100 return non-negative results for negative value in Python, so the suffix lookup in ordinal() always landed on 'th' for negative numbers (e.g. ordinal(-1) gave '-1th', ordinal(-21) gave '-21th'). Compute the digit off abs(value) instead, while still formatting the original signed value. --- src/humanize/number.py | 5 ++++- tests/test_number.py | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/humanize/number.py b/src/humanize/number.py index 52a5356a..bd40b7be 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -113,6 +113,8 @@ def ordinal(value: NumberOrString, gender: str = "male") -> str: '101st' >>> ordinal(111) '111th' + >>> ordinal(-1) + '-1st' >>> ordinal("something else") 'something else' >>> ordinal([1, 2, 3]) == "[1, 2, 3]" @@ -136,7 +138,8 @@ def ordinal(value: NumberOrString, gender: str = "male") -> str: except (TypeError, ValueError): return str(value) gender = "male" if gender == "male" else "female" - digit = 0 if value % 100 in (11, 12, 13) else value % 10 + n = abs(value) + digit = 0 if n % 100 in (11, 12, 13) else n % 10 return f"{value}{P_(*_ORDINAL_SUFFIXES[gender][digit])}" diff --git a/tests/test_number.py b/tests/test_number.py index 5fb12fa6..fc056007 100644 --- a/tests/test_number.py +++ b/tests/test_number.py @@ -25,6 +25,16 @@ ("102", "102nd"), ("103", "103rd"), ("111", "111th"), + (-1, "-1st"), + (-2, "-2nd"), + (-3, "-3rd"), + (-4, "-4th"), + (-11, "-11th"), + (-12, "-12th"), + (-13, "-13th"), + (-21, "-21st"), + (-100, "-100th"), + (-111, "-111th"), ("something else", "something else"), (None, "None"), (math.nan, "NaN"),