Skip to content

Instantly share code, notes, and snippets.

@ei-grad
Created January 14, 2017 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ei-grad/b290dc761ae253af69438bbb94d82683 to your computer and use it in GitHub Desktop.
Save ei-grad/b290dc761ae253af69438bbb94d82683 to your computer and use it in GitHub Desktop.
Answer to "How to print number with commas as thousands separators?"
# http://stackoverflow.com/a/39301723/2649222
def format_money(f, delimiter=',', frac_digits=2):
'''
>>> format_money(1.7777)
'1.78'
>>> format_money(-1.7777)
'-1.78'
>>> format_money(12.7777)
'12.78'
>>> format_money(-12.7777)
'-12.78'
>>> format_money(123.7777)
'123.78'
>>> format_money(-123.7777)
'-123.78'
>>> format_money(1234.7777)
'1,234.78'
>>> format_money(-1234.7777)
'-1,234.78'
>>> format_money(12345.7777)
'12,345.78'
>>> format_money(-12345.7777)
'-12,345.78'
>>> format_money(123456.7777)
'123,456.78'
>>> format_money(-123456.7777)
'-123,456.78'
>>> format_money(1234567.7777)
'1,234,567.78'
>>> format_money(-1234567.7777)
'-1,234,567.78'
>>> format_money(12345678.7777)
'12,345,678.78'
>>> format_money(-12345678.7777)
'-12,345,678.78'
>>> format_money(123456789.7777)
'123,456,789.78'
>>> format_money(-123456789.7777)
'-123,456,789.78'
'''
negative_fix = int(f < 0)
s = '%.*f' % (frac_digits, f)
if len(s) < 5 + frac_digits + negative_fix:
return s
l = list(s)
l_fix = l[negative_fix:]
p = len(l_fix) - frac_digits - 5
l_fix[p::-3] = [i + delimiter for i in l_fix[p::-3]]
return ''.join(l[:negative_fix] + l_fix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment