From 01d5c507b857835abf18a6da3a70a8a709a6327a Mon Sep 17 00:00:00 2001 From: yu2971512385-ui <287936273+yu2971512385-ui@users.noreply.github.com> Date: Tue, 22 Sep 2026 22:52:58 +0800 Subject: [PATCH] Fix ordinal() suffix for negative numbers Python's % on a negative operand returns the remainder of the wrong digit (-1 % 10 == 9), so every negative value picked the "th" suffix: ordinal(-1) returned "-1th" and ordinal(-3) returned "-3th". Take the last digits of the magnitude instead, which keeps the 11/12/13 exception working for negative values too. --- src/humanize/number.py | 6 +++++- tests/test_number.py | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/humanize/number.py b/src/humanize/number.py index 52a5356a..57e92966 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -136,7 +136,11 @@ 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 + # Take the last digits of the magnitude: Python's % on a negative number + # returns a positive remainder of the wrong digit (-1 % 10 == 9), which + # picked the "th" suffix for every negative value, e.g. "-1th". + magnitude = abs(value) + digit = 0 if magnitude % 100 in (11, 12, 13) else magnitude % 10 return f"{value}{P_(*_ORDINAL_SUFFIXES[gender][digit])}" diff --git a/tests/test_number.py b/tests/test_number.py index 5fb12fa6..9d7000c5 100644 --- a/tests/test_number.py +++ b/tests/test_number.py @@ -25,6 +25,15 @@ ("102", "102nd"), ("103", "103rd"), ("111", "111th"), + ("-1", "-1st"), + ("-2", "-2nd"), + ("-3", "-3rd"), + ("-4", "-4th"), + ("-11", "-11th"), + ("-12", "-12th"), + ("-13", "-13th"), + ("-21", "-21st"), + ("-111", "-111th"), ("something else", "something else"), (None, "None"), (math.nan, "NaN"),