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"),