Welcome, guest | Sign In | My Account | Store | Cart

This function takes a number (integer or float) and returns a string with the integer portion grouped by thousands and the decimal portion rounded or padded to given number of decimal places.

Python, 19 lines
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19``` ```def number_format(num, places=0): """Format a number with grouped thousands and given decimal places""" places = max(0,places) tmp = "%.*f" % (places, num) point = tmp.find(".") integer = (point == -1) and tmp or tmp[:point] decimal = (point != -1) and tmp[point:] or "" count = 0 formatted = [] for i in range(len(integer), 0, -1): count += 1 formatted.append(integer[i - 1]) if count % 3 == 0 and i - 1: formatted.append(",") integer = "".join(formatted[::-1]) return integer+decimal ```

This function is based loosely on PHP's number_format function.

Edward Hartfield (author) 17 years, 7 months ago

Relic. I just noticed that I initialize but never use a variable "commas". I forgot to take that out before submitting the recipe. (It's a relic of the function's evolution)

Edward Hartfield (author) 17 years, 7 months ago

Relic Relic. I fixed it. I didn't know I could edit the code after I submitted. Wish I could find a way to remove this redundant comment!

Chris Arndt 17 years, 7 months ago

RTFM. It's all in the standard library:

``````import locale

def number_format(num, places=0):
return locale.format("%.*f", (places, num), True)

if __name__ == '__main__':
locale.setlocale(locale.LC_NUMERIC, '')
print number_format(12345.6789, 2)
# will print '12.345,68' (rounded!) in German locale
``````

References:

http://www.python.org/doc/current/lib/module-locale.html

http://www.python.org/doc/current/lib/typesseq-strings.html (see item 4 in 3rd paragraph)

BTW: the "F" in RTFM should be read as "fine" or "fantastic" here!

Edward Hartfield (author) 17 years, 7 months ago

Thanks, Chris. I found this code after I submitted this recipe. Hopefully, when the editor's get a round tuit, they'll just delete it.

Kumar McMillan 17 years, 5 months ago

probably good to keep the recipe up. silly but since I knew PHP before Python I actually got this link from google and thus found out about the locale module (I knew there was something in std lib but didn't know which module). so ... maybe one should leave the recipe up for us scarred PHP veterans? :)

sasa sasa 15 years, 7 months ago

there's a bug! The code does not handle negative numbers properly. It will format -500 as -,500. I've made a fix, but this site won't let me post it using a ecode tag.

 Created by Edward Hartfield on Wed, 8 Feb 2006 (PSF)

### Tags

▶ Show machine tags (4)

### Required Modules

• (none specified)