Skip to content

Commit

Permalink
Merge pull request #52 from Luflosi/fix-intcomma-with-str-and-ndigits
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk authored Aug 30, 2022
2 parents e0a0ef0 + 33005e5 commit d8e2739
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
19 changes: 12 additions & 7 deletions src/humanize/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
'1,234.55'
>>> intcomma(14308.40, 1)
'14,308.4'
>>> intcomma("14308.40", 1)
'14,308.4'
>>> intcomma(None)
'None'
Expand All @@ -131,7 +133,11 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
sep = thousands_separator()
try:
if isinstance(value, str):
float(value.replace(sep, ""))
value = value.replace(sep, "")
if "." in value:
value = float(value)
else:
value = int(value)
else:
float(value)
except (TypeError, ValueError):
Expand All @@ -141,12 +147,11 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
orig = "{0:.{1}f}".format(value, ndigits)
else:
orig = str(value)

new = re.sub(r"^(-?\d+)(\d{3})", rf"\g<1>{sep}\g<2>", orig)
if orig == new:
return new

return intcomma(new)
while True:
new = re.sub(r"^(-?\d+)(\d{3})", rf"\g<1>{sep}\g<2>", orig)
if orig == new:
return new
orig = new


powers = [10**x for x in (3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 100)]
Expand Down
4 changes: 4 additions & 0 deletions tests/test_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ def test_ordinal(test_input: str, expected: str) -> None:
(["10311"], "10,311"),
(["1000000"], "1,000,000"),
(["1234567.1234567"], "1,234,567.1234567"),
(["1234567.1234567", 0], "1,234,567"),
(["1234567.1234567", 1], "1,234,567.1"),
(["1234567.1234567", 10], "1,234,567.1234567000"),
(["1234567", 1], "1,234,567.0"),
([None], "None"),
([14308.40], "14,308.4"),
([14308.40, None], "14,308.4"),
Expand Down

0 comments on commit d8e2739

Please sign in to comment.