Skip to content

Instantly share code, notes, and snippets.

@lunareve
Created January 22, 2018 20:29
Show Gist options
  • Save lunareve/613bc07f6e3b0ea36a8a03ac460a3de7 to your computer and use it in GitHub Desktop.
Save lunareve/613bc07f6e3b0ea36a8a03ac460a3de7 to your computer and use it in GitHub Desktop.
def number_groupings(number):
"""Given an integer, return a string representation of that integer
with ',' at the appropriate groupings to indicate thousands places.
>>> number_groupings(1234)
'1,234'
>>> number_groupings(12345678)
'12,345,678'
>>> number_groupings(-12345)
'-12,345'
"""
strnumber = str(number)
start = len(strnumber)%3
if start == 0:
numstring = strnumber[0:3]
start = 3
else:
numstring = strnumber[0:start]
for i in range(start, len(strnumber), 3):
numstring += ',' + strnumber[i:i+3]
return numstring
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment