Skip to content
Open
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
26 changes: 25 additions & 1 deletion src/humanize/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,31 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
if ndigits is not None:
result = f"{value:,.{ndigits}f}"
else:
result = f"{value:,}"
if isinstance(value, float) and value == int(value):
# Whole-number float: format as int to avoid trailing .0
result = f"{int(value):,}"
elif (
isinstance(value, float)
and value != 0
and (abs(value) >= 1e15 or abs(value) <= 1e-5)
):
# Python repr uses scientific notation for very large/small floats,
# which breaks the , format specifier. Use Decimal for proper formatting.
from decimal import Decimal

d = Decimal(str(value))
formatted = f"{d:f}"
if "." in formatted:
int_part, dec_part = formatted.split(".")
dec_part = dec_part.rstrip("0")
if dec_part:
result = f"{int(int_part):,}.{dec_part}"
else:
result = f"{int(int_part):,}"
else:
result = f"{int(formatted):,}"
else:
result = f"{value:,}"
if thousands_sep != "," or decimal_sep != ".":
result = result.translate(str.maketrans(",.", thousands_sep + decimal_sep))
return result
Expand Down