Skip to content

Commit d8e2739

Browse files
authored
Merge pull request #52 from Luflosi/fix-intcomma-with-str-and-ndigits
2 parents e0a0ef0 + 33005e5 commit d8e2739

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

src/humanize/number.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
117117
'1,234.55'
118118
>>> intcomma(14308.40, 1)
119119
'14,308.4'
120+
>>> intcomma("14308.40", 1)
121+
'14,308.4'
120122
>>> intcomma(None)
121123
'None'
122124
@@ -131,7 +133,11 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
131133
sep = thousands_separator()
132134
try:
133135
if isinstance(value, str):
134-
float(value.replace(sep, ""))
136+
value = value.replace(sep, "")
137+
if "." in value:
138+
value = float(value)
139+
else:
140+
value = int(value)
135141
else:
136142
float(value)
137143
except (TypeError, ValueError):
@@ -141,12 +147,11 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
141147
orig = "{0:.{1}f}".format(value, ndigits)
142148
else:
143149
orig = str(value)
144-
145-
new = re.sub(r"^(-?\d+)(\d{3})", rf"\g<1>{sep}\g<2>", orig)
146-
if orig == new:
147-
return new
148-
149-
return intcomma(new)
150+
while True:
151+
new = re.sub(r"^(-?\d+)(\d{3})", rf"\g<1>{sep}\g<2>", orig)
152+
if orig == new:
153+
return new
154+
orig = new
150155

151156

152157
powers = [10**x for x in (3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 100)]

tests/test_number.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ def test_ordinal(test_input: str, expected: str) -> None:
4646
(["10311"], "10,311"),
4747
(["1000000"], "1,000,000"),
4848
(["1234567.1234567"], "1,234,567.1234567"),
49+
(["1234567.1234567", 0], "1,234,567"),
50+
(["1234567.1234567", 1], "1,234,567.1"),
51+
(["1234567.1234567", 10], "1,234,567.1234567000"),
52+
(["1234567", 1], "1,234,567.0"),
4953
([None], "None"),
5054
([14308.40], "14,308.4"),
5155
([14308.40, None], "14,308.4"),

0 commit comments

Comments
 (0)