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.
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.
Tags: text
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)
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!
RTFM. It's all in the standard library:
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!
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.
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? :)
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.