Skip to content
Closed
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
7 changes: 7 additions & 0 deletions src/humanize/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
__lazy_modules__ = {"bisect"}

import bisect
from decimal import Decimal

from .i18n import _gettext as _
from .i18n import _gettext_noop as N_
Expand Down Expand Up @@ -198,6 +199,12 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
result = f"{value:,.{ndigits}f}"
else:
result = f"{value:,}"
if isinstance(value, float) and ("e" in result or "E" in result):
# repr-style float formatting switches to scientific notation
# (>= 1e16, < 1e-4); expand it so digits are still grouped.
result = format(Decimal(repr(value)), ",f")
if value.is_integer():
result += ".0"
if thousands_sep != "," or decimal_sep != ".":
result = result.translate(str.maketrans(",.", thousands_sep + decimal_sep))
return result
Expand Down
8 changes: 8 additions & 0 deletions tests/test_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,14 @@ def test_ordinal(test_input: str, expected: str) -> None:
([-math.inf], "-Inf"),
(["nan"], "NaN"),
(["-inf"], "-Inf"),
# Floats whose repr uses scientific notation stay expanded (issue #431)
([1e16], "10,000,000,000,000,000.0"),
([1.5e20], "150,000,000,000,000,000,000.0"),
([-1e16], "-10,000,000,000,000,000.0"),
([1e16, 0], "10,000,000,000,000,000"),
([0.00001], "0.00001"),
([1.23e-5], "0.0000123"),
([1234.5e15], "1,234,500,000,000,000,000.0"),
],
)
def test_intcomma(
Expand Down