Skip to content
Open
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
10 changes: 6 additions & 4 deletions src/humanize/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,10 +361,12 @@ def fractional(value: NumberOrString) -> str:
frac = Fraction(number - whole_number).limit_denominator(1000)
numerator = frac.numerator
denominator = frac.denominator
if whole_number and not numerator and denominator == 1:
# this means that an integer was passed in
# (or variants of that integer like 1.0000)
return f"{whole_number:.0f}"
if denominator == 1:
# The fractional part reduced to a whole number: either an integer
# was passed in (e.g. 1 or 1.0000, giving 0/1), or the fractional part
# rounded up to 1/1 (e.g. 2.9999999). Fold it into the integer part
# instead of emitting a degenerate "0/1" or "2 1/1".
return f"{whole_number + numerator:.0f}"

if not whole_number:
return f"{numerator:.0f}/{denominator:.0f}"
Expand Down
5 changes: 5 additions & 0 deletions tests/test_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,11 @@ def test_apnumber(test_input: int | str, expected: str) -> None:
(-1.3, "-1 3/10"),
(-2.5, "-2 1/2"),
(-0.5, "-1/2"),
(0, "0"),
(0.0, "0"),
(2.9999999, "3"),
(0.9999999, "1"),
(-2.9999999, "-3"),
],
)
def test_fractional(test_input: float | str, expected: str) -> None:
Expand Down