Skip to content

Commit

Permalink
Fix intword for negative numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
vishket committed Jul 8, 2022
1 parent 5dc4b82 commit bda2c5b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/humanize/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,11 @@ def intword(value: NumberOrString, format: str = "%.1f") -> str:
except (TypeError, ValueError):
return str(value)

is_negative = value < 0

if is_negative:
value *= -1

if value < powers[0]:
return str(value)
for ordinal, power in enumerate(powers[1:], 1):
Expand All @@ -221,7 +226,8 @@ def intword(value: NumberOrString, format: str = "%.1f") -> str:
return (
" ".join([format, _ngettext(singular, plural, math.ceil(chopped))])
) % chopped
return str(value)

return "-" + str(value) if is_negative else str(value)


def apnumber(value: NumberOrString) -> str:
Expand Down
7 changes: 7 additions & 0 deletions tests/test_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,24 +75,31 @@ def test_intword_powers() -> None:
@pytest.mark.parametrize(
"test_args, expected",
[
(["0"], "0"),
(["100"], "100"),
(["-100"], "-100"),
(["1000"], "1.0 thousand"),
(["12400"], "12.4 thousand"),
(["12490"], "12.5 thousand"),
(["1000000"], "1.0 million"),
(["-1000000"], "-1.0 million"),
(["1200000"], "1.2 million"),
(["1290000"], "1.3 million"),
(["999999999"], "1.0 billion"),
(["1000000000"], "1.0 billion"),
(["-1000000000"], "-1.0 billion"),
(["2000000000"], "2.0 billion"),
(["999999999999"], "1.0 trillion"),
(["1000000000000"], "1.0 trillion"),
(["6000000000000"], "6.0 trillion"),
(["-6000000000000"], "-6.0 trillion"),
(["999999999999999"], "1.0 quadrillion"),
(["1000000000000000"], "1.0 quadrillion"),
(["1300000000000000"], "1.3 quadrillion"),
(["-1300000000000000"], "-1.3 quadrillion"),
(["3500000000000000000000"], "3.5 sextillion"),
(["8100000000000000000000000000000000"], "8.1 decillion"),
(["-8100000000000000000000000000000000"], "-8.1 decillion"),
([None], "None"),
(["1230000", "%0.2f"], "1.23 million"),
([10**101], "1" + "0" * 101),
Expand Down

0 comments on commit bda2c5b

Please sign in to comment.