Skip to content

Commit

Permalink
Merge pull request #41 from vishket/update-intword
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Jul 11, 2022
2 parents 5dc4b82 + 4c76d35 commit e705e43
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
21 changes: 17 additions & 4 deletions src/humanize/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,23 +205,36 @@ def intword(value: NumberOrString, format: str = "%.1f") -> str:
except (TypeError, ValueError):
return str(value)

if value < 0:
value *= -1
negative_prefix = "-"
else:
negative_prefix = ""

if value < powers[0]:
return str(value)
return negative_prefix + str(value)
for ordinal, power in enumerate(powers[1:], 1):
if value < power:
chopped = value / float(powers[ordinal - 1])
if float(format % chopped) == float(10**3):
chopped = value / float(powers[ordinal])
singular, plural = human_powers[ordinal]
return (
" ".join([format, _ngettext(singular, plural, math.ceil(chopped))])
negative_prefix
+ " ".join(
[format, _ngettext(singular, plural, math.ceil(chopped))]
)
) % chopped
else:
singular, plural = human_powers[ordinal - 1]
return (
" ".join([format, _ngettext(singular, plural, math.ceil(chopped))])
negative_prefix
+ " ".join(
[format, _ngettext(singular, plural, math.ceil(chopped))]
)
) % chopped
return str(value)

return negative_prefix + 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 e705e43

Please sign in to comment.