From 0e06160bfe989aeee06b17b8df2e39b2b688dcc8 Mon Sep 17 00:00:00 2001 From: Devraj Pal Date: Fri, 18 Sep 2026 23:45:50 +0530 Subject: [PATCH] Fix ordinal() suffix for negative numbers ordinal() computed the suffix from value % 10 and value % 100, but Python's modulo on a negative number gave the wrong digit, so e.g. ordinal(-9) was "-9st" and ordinal(-1) was "-1th". Use the magnitude instead. --- 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..33c97529 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -136,7 +136,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 + # Use the magnitude so negatives pick the right suffix: Python's modulo of a + # negative number would otherwise map e.g. -9 to "st" and -1 to "th". + 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..c24b5ef5 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"), + ("-9", "-9th"), + ("-11", "-11th"), + ("-21", "-21st"), + ("-22", "-22nd"), + ("-23", "-23rd"), + ("-111", "-111th"), ("something else", "something else"), (None, "None"), (math.nan, "NaN"),