Skip to content

Fix fractional() formatting 0 as "0/1" instead of "0" - #374

Open
Arunendra21 wants to merge 1 commit into
python-humanize:mainfrom
Arunendra21:fix-fractional-zero
Open

Fix fractional() formatting 0 as "0/1" instead of "0"#374
Arunendra21 wants to merge 1 commit into
python-humanize:mainfrom
Arunendra21:fix-fractional-zero

Conversation

@Arunendra21

Copy link
Copy Markdown

Bug

fractional(0) returns "0/1", while every other whole number returns a bare number:

>>> import humanize
>>> humanize.fractional(0)
'0/1'      # expected '0'
>>> humanize.fractional(1)
'1'
>>> humanize.fractional(2)
'2'
>>> humanize.fractional(-2)
'-2'

Cause

The whole-number branch is gated on whole_number being truthy:

if whole_number and not numerator and denominator == 1:
    return f"{whole_number:.0f}"

whole_number is 0 (falsy) for the value 0, so it falls through to the if not whole_number: branch and is rendered as numerator/denominator = 0/1.

Fix

The branch only needs to check that no fractional part remains, i.e. numerator == 0, which is true for any whole number including 0. When the numerator is 0 the fraction is always 0/1, so the denominator == 1 check was redundant and is dropped.

Verified against all existing test_fractional cases (no changes) plus new cases for 0, 0.0 and "0".

fractional(0) returned "0/1" because the whole-number branch was gated on
`whole_number` being truthy, which excludes 0. Every other integer (1, 2,
-2, and so on) already returns a bare number, so 0 was the odd one out.

The branch really just needs to check that no fractional part remains
(numerator == 0), which holds for any whole number including 0. When the
numerator is 0 the fraction is always 0/1, so the denominator == 1 check
was redundant and is dropped.

Adds test cases for 0, 0.0 and "0".

Co-authored-by: eeshsaxena <eeshsaxena@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant