From 685d378a681c57f48c75c58364dc4873f421ef87 Mon Sep 17 00:00:00 2001 From: MildlyMeticulous <302576729+MildlyMeticulous@users.noreply.github.com> Date: Fri, 24 Jul 2026 22:06:53 -0700 Subject: [PATCH] fix: correct ordinal suffix for negative numbers Python % is not sign-symmetric: -1 % 10 is 9, so ordinal(-1) selected the "th" suffix and returned "-1th" instead of "-1st". Take the suffix from abs(value); -11 through -13 still correctly get "th". --- 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 2fb22c6..4e7fb3f 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -109,7 +109,10 @@ 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 + # The suffix follows the magnitude, and Python's % is not sign-symmetric: + # -1 % 10 is 9, which would pick "th" instead of "st". + magnitude = abs(value) + digit = 0 if magnitude % 100 in (11, 12, 13) else magnitude % 10 return f"{value}{P_(f'{digit} ({gender})', _ORDINAL_SUFFIXES[digit])}" diff --git a/tests/test_number.py b/tests/test_number.py index 78639c3..8ebf0ea 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"), + ("-101", "-101st"), + ("-111", "-111th"), ("something else", "something else"), (None, "None"), (math.nan, "NaN"),