views:

256

answers:

4

For example:

>> print numberFormat(1234)
>> 1,234

Or is there a built-in function in Python that does this?

Thanks!

+12  A: 

locale.format()

Don't forget to set the locale appropriately first.

Ignacio Vazquez-Abrams
+3  A: 

Stripped from webpy utils:

def commify(n): """ Add commas to an integer n.

    >>> commify(1)
    '1'
    >>> commify(123)
    '123'
    >>> commify(1234)
    '1,234'
    >>> commify(1234567890)
    '1,234,567,890'
    >>> commify(123.0)
    '123.0'
    >>> commify(1234.5)
    '1,234.5'
    >>> commify(1234.56789)
    '1,234.56789'
    >>> commify('%.2f' % 1234.5)
    '1,234.50'
    >>> commify(None)
    >>>

"""
if n is None: return None
n = str(n)
if '.' in n:
    dollars, cents = n.split('.')
else:
    dollars, cents = n, None

r = []
for i, c in enumerate(str(dollars)[::-1]):
    if i and (not (i % 3)):
        r.insert(0, ',')
    r.insert(0, c)
out = ''.join(r)
if cents:
    out += '.' + cents
return out

There are other solutions here.

systempuntoout
+1 despite the docstring, looks like it handles floating point as well as integer numbers. The use of the variable names "dollars" and "cents", aside from being somewhat overly application-centric, seem to support this hypothesis. Very Python version portable, as presented will work back to version 2.3, and if the `enumerate()` iterator was replaced with the something equivalent, all the way back to version 2.0.
martineau
For Python 2.4+, the `str(dollars)[::-1]` could be replaced with the more readable `reversed(str(dollars))`.
martineau
@martineau nice review, I use this function on Google App Engine where Python is limited to 2.5 version out of the box.
systempuntoout
+4  A: 

Use locale.format() on the integer, but beware of the current locale on your environment. Some environments may not have this set or set to something that won't give you a commafied result.

Here's some code I had to write to deal with this exact issue. It'll automatically set the locale for you depending on your platform:

try:
    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') #use locale.format for commafication
except locale.Error:
    locale.setlocale(locale.LC_ALL, '') #set to default locale (works on windows)

score = locale.format('%d', player['score'], True)
Aphex
+11  A: 

No one so far has mentioned the new ',' option which was added in version 2.7 to the Format Specification Mini-Language -- see PEP 378: Format Specifier for Thousands Separator in the What's New in Python 2.7 document. It's easy to use because you don't have to mess around with locale (but limited for internationalization due to that, see the original PEP 378). It works with floats, ints, and decimals -- and all the other formatting features provided for in the mini-language spec.

Sample usage:

print format(1234, ",d")   # 1,234
print "{:,d}".format(1234) # 1,234

Note: While this new feature is definitely handy, it's actually not all that much harder to use the locale module, as several others have suggested. The advantage is that then numeric output can then be made to automatically follow the proper thousands (and other) separator conventions used in various countries when outputting things like numbers, dates, and times. It's also very easy to put the default settings from your computer into effect without learning a bunch of language and country codes. All you need to do is:

import locale
locale.setlocale(locale.LC_ALL, '') # empty string for platform's default setting

After doing that you can just use a plain old 'n' type code for outputting numbers. Where I am we use commas as the thousand separator, so after executing the above, this is the output:

print format(1234, "n")   # 1,234
print "{:n}".format(1234) # 1,234

In other large parts of the world, periods instead of commas are used for this purpose, so setting the default locale there (or explicitly specifying the code for one of them here on my computer) produces the following:

print format(1234, "n")   # 1.234
print "{:n}".format(1234) # 1.234

Output based on the 'd' or ',d' formatting type specifier is unaffected by the use (or non-use) of setlocale().

martineau