Skip to content

Commit 3af1a68

Browse files
committed
Fix ordinal() suffix for negative integers
ordinal() selected the suffix using value % 10 and value % 100, but Python's modulo on negative numbers is non-negative (e.g. -1 % 10 == 9), so negative inputs got the wrong suffix: ordinal(-1) returned '-1th' instead of '-1st', ordinal(-21) returned '-21th' instead of '-21st', etc. The docstring states it works for any integer, so compute the suffix from abs(value). Add regression tests for negative ordinals.
1 parent 0a06a3d commit 3af1a68

2 files changed

Lines changed: 15 additions & 1 deletion

File tree

src/humanize/number.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,11 @@ def ordinal(value: NumberOrString, gender: str = "male") -> str:
107107
except (TypeError, ValueError):
108108
return str(value)
109109
gender = "male" if gender == "male" else "female"
110-
digit = 0 if value % 100 in (11, 12, 13) else value % 10
110+
# Use the magnitude for suffix selection: Python's modulo on negative
111+
# numbers is non-negative (e.g. -1 % 10 == 9), which would otherwise
112+
# pick the wrong suffix and produce "-1th" instead of "-1st".
113+
abs_value = abs(value)
114+
digit = 0 if abs_value % 100 in (11, 12, 13) else abs_value % 10
111115
return f"{value}{P_(f'{digit} ({gender})', _ORDINAL_SUFFIXES[digit])}"
112116

113117

tests/test_number.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,16 @@
2525
("102", "102nd"),
2626
("103", "103rd"),
2727
("111", "111th"),
28+
("-1", "-1st"),
29+
("-2", "-2nd"),
30+
("-3", "-3rd"),
31+
("-4", "-4th"),
32+
("-11", "-11th"),
33+
("-12", "-12th"),
34+
("-13", "-13th"),
35+
("-21", "-21st"),
36+
("-101", "-101st"),
37+
("-111", "-111th"),
2838
("something else", "something else"),
2939
(None, "None"),
3040
(math.nan, "NaN"),

0 commit comments

Comments
 (0)