Skip to content

Commit 331b4c6

Browse files
committed
fractional: stop printing two minus signs for a negative mixed number
int() truncates toward zero, so int(-1.3) is -1 and (-1.3) - (-1) is -0.3, which Fraction turns into -3/10. Both the whole-number part and the numerator end up signed and the output reads as "-1 -3/10". The minus sign already rides on the whole-number part; absorb it from the numerator so the result is the conventional "-1 3/10". Added a few negative cases to test_fractional. Signed-off-by: Charlie Tonneslan <cst0520@gmail.com>
1 parent 013969a commit 331b4c6

2 files changed

Lines changed: 9 additions & 1 deletion

File tree

src/humanize/number.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,12 @@ def fractional(value: NumberOrString) -> str:
367367
if not whole_number:
368368
return f"{numerator:.0f}/{denominator:.0f}"
369369

370-
return f"{whole_number:.0f} {numerator:.0f}/{denominator:.0f}"
370+
# int() truncates toward zero, so for a negative number both
371+
# whole_number and numerator carry the minus sign, which prints as
372+
# "-1 -3/10". The sign already rides on the whole part; absorb it
373+
# from the fractional part so the result reads as a normal mixed
374+
# fraction.
375+
return f"{whole_number:.0f} {abs(numerator):.0f}/{denominator:.0f}"
371376

372377

373378
def scientific(value: NumberOrString, precision: int = 2) -> str:

tests/test_number.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,9 @@ def test_apnumber(test_input: int | str, expected: str) -> None:
183183
(-math.inf, "-Inf"),
184184
("nan", "NaN"),
185185
("-inf", "-Inf"),
186+
(-1.3, "-1 3/10"),
187+
(-2.5, "-2 1/2"),
188+
(-0.5, "-1/2"),
186189
],
187190
)
188191
def test_fractional(test_input: float | str, expected: str) -> None:

0 commit comments

Comments
 (0)