diff --git a/src/humanize/number.py b/src/humanize/number.py index f4dcb05..9ae943b 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -107,7 +107,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 + # Use the magnitude for suffix selection: Python's modulo on negative + # numbers is non-negative (e.g. -1 % 10 == 9), which would otherwise + # pick the wrong suffix and produce "-1th" instead of "-1st". + abs_value = abs(value) + digit = 0 if abs_value % 100 in (11, 12, 13) else abs_value % 10 return f"{value}{P_(f'{digit} ({gender})', _ORDINAL_SUFFIXES[digit])}" diff --git a/tests/test_number.py b/tests/test_number.py index cb74fcf..a947eba 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"),