Skip to content

Commit c5153f2

Browse files
committed
Fix intcomma exponential notation for large floats
1 parent a950045 commit c5153f2

2 files changed

Lines changed: 11 additions & 0 deletions

File tree

‎src/humanize/number.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,10 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
197197

198198
if ndigits is not None:
199199
result = f"{value:,.{ndigits}f}"
200+
elif isinstance(value, float) and abs(value) >= 1e16:
201+
# ``f"{value:,}"`` switches to exponential notation for large
202+
# floats, dropping the comma grouping; format them in full instead.
203+
result = f"{value:,.1f}"
200204
else:
201205
result = f"{value:,}"
202206
if thousands_sep != "," or decimal_sep != ".":

‎tests/test_number.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,13 @@ def test_intcomma_large_integer(sign: int) -> None:
9090
assert humanize.intcomma(value) == expected
9191

9292

93+
def test_intcomma_large_float() -> None:
94+
# Formatting a float with "," switches to exponential notation at 1e16,
95+
# which drops the comma grouping entirely.
96+
assert humanize.intcomma(1e16) == "10,000,000,000,000,000.0"
97+
assert humanize.intcomma(-1e16) == "-10,000,000,000,000,000.0"
98+
99+
93100
def test_intword_powers() -> None:
94101
# make sure that powers & human_powers have the same number of items
95102
assert len(number.powers) == len(number.human_powers)

0 commit comments

Comments
 (0)