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
27 changes: 23 additions & 4 deletions src/humanize/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,10 +255,29 @@ def intword(value: NumberOrString, format: str = "%.1f") -> str:
chopped = value / power
rounded_value = float(format % chopped)

if not largest_ordinal and rounded_value * power == powers[ordinal + 1]:
# After rounding, we end up just at the next power
ordinal += 1
rounded_value = 1.0
if not largest_ordinal and rounded_value >= 1000:
next_power = powers[ordinal + 1]
if next_power == power * 1000:
# After rounding, we end up just at the next power
ordinal += 1
rounded_value = 1.0
else:
# `powers` has a gap between this unit and the next one (e.g.
# decillion to googol), so there is no unit for "1000+ of the
# current one". Only bump to the next unit if the value is
# close enough to actually round up to it; otherwise there is
# no English name for this magnitude. Some locales translate the
# current unit to a larger local scale, so allow those to keep
# using the translated unit instead of falling back.
next_rounded_value = float(format % (value / next_power))
if next_rounded_value >= 1.0:
ordinal += 1
rounded_value = next_rounded_value
else:
singular, plural = human_powers[ordinal]
translated_unit = _ngettext(singular, plural, math.ceil(rounded_value))
if translated_unit in (singular, plural):
return f"{negative_prefix}{value}"

singular, plural = human_powers[ordinal]
unit = _ngettext(singular, plural, math.ceil(rounded_value))
Expand Down
17 changes: 14 additions & 3 deletions tests/test_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,21 @@ def test_intword_powers() -> None:
(["3500000000000000000000"], "3.5 sextillion"),
(["8100000000000000000000000000000000"], "8.1 decillion"),
(["-8100000000000000000000000000000000"], "-8.1 decillion"),
([1_000_000_000_000_000_000_000_000_000_000_000_000], "1000.0 decillion"),
([1_100_000_000_000_000_000_000_000_000_000_000_000], "1100.0 decillion"),
([2_100_000_000_000_000_000_000_000_000_000_000_000], "2100.0 decillion"),
(
[1_000_000_000_000_000_000_000_000_000_000_000_000],
"1000000000000000000000000000000000000",
),
(
[1_100_000_000_000_000_000_000_000_000_000_000_000],
"1100000000000000000000000000000000000",
),
(
[2_100_000_000_000_000_000_000_000_000_000_000_000],
"2100000000000000000000000000000000000",
),
([2e100], "2.0 googol"),
([10**50], str(10**50)),
([10**100 - 10**93], "1.0 googol"),
([None], "None"),
(["1230000", "%0.2f"], "1.23 million"),
([10**100], "1.0 googol"),
Expand Down