Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/humanize/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])}"


Expand Down
9 changes: 9 additions & 0 deletions tests/test_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down