From 17a5522503ec7ff0f7d0d6cc07296706ae44e97e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=87=91=E8=B1=86?= Date: Mon, 5 Oct 2026 21:32:19 +0800 Subject: [PATCH] ordinal: fix suffix for negative numbers The suffix tables are indexed with value % 10 (and the 11/12/13 special case with value % 100), but Python's modulo maps negative numbers outside those ranges: -1 % 10 == 9, so every negative number got the generic 'th' suffix: >>> ordinal(-1) '-1th' >>> ordinal(-101) '-101th' Select the suffix on the absolute value so negative ordinals get the same suffix as their positive counterparts ('-1st', '-101st'). --- src/humanize/number.py | 7 +++++-- tests/test_number.py | 7 +++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/humanize/number.py b/src/humanize/number.py index 6611a21..a112065 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -79,9 +79,12 @@ def ordinal(value, gender="male"): P_("8 (female)", "th"), P_("9 (female)", "th"), ) - if value % 100 in (11, 12, 13): # special case + # Python's modulo keeps negative numbers out of the 0-9/11-13 ranges the + # suffix tables are indexed with, so select on the absolute value + n = abs(value) + if n % 100 in (11, 12, 13): # special case return f"{value}{t[0]}" - return f"{value}{t[value % 10]}" + return f"{value}{t[n % 10]}" def intcomma(value, ndigits=None): diff --git a/tests/test_number.py b/tests/test_number.py index eec6217..54cdbf7 100644 --- a/tests/test_number.py +++ b/tests/test_number.py @@ -20,6 +20,13 @@ ("102", "102nd"), ("103", "103rd"), ("111", "111th"), + ("-1", "-1st"), + ("-2", "-2nd"), + ("-3", "-3rd"), + ("-4", "-4th"), + ("-11", "-11th"), + ("-111", "-111th"), + ("-101", "-101st"), ("something else", "something else"), (None, None), ],