E
Edward Hartfield
I'm am relatively new to Python but use it daily. Today, I went looking
for a function, like PHP's number_function, that will take a number and
return a string with number formatted with grouped thousands and the
decimal portion rounded to a given number of places. This is certainly
needed when you want to take a floating-point value from a database and
display it as currency, for instance. I could not find what I was
looking for so I wrote the following function. I hope either (a) I've
provided something useful or (b) someone can tell me what I *should*
have done! Thanks.
import math
def number_format(num, places=0):
"""Format a number with grouped thousands and given decimal places"""
#is_negative = (num < 0)
#if is_negative:
# num = -num
places = max(0,places)
tmp = "%.*f" % (places, num)
point = tmp.find(".")
integer = (point == -1) and tmp or tmp[oint]
decimal = (point != -1) and tmp[point:] or ""
count = commas = 0
formatted = []
for i in range(len(integer) - 1, 0, -1):
count += 1
formatted.append(integer)
if count % 3 == 0:
formatted.append(",")
integer = "".join(formatted[::-1])
return integer+decimal
for a function, like PHP's number_function, that will take a number and
return a string with number formatted with grouped thousands and the
decimal portion rounded to a given number of places. This is certainly
needed when you want to take a floating-point value from a database and
display it as currency, for instance. I could not find what I was
looking for so I wrote the following function. I hope either (a) I've
provided something useful or (b) someone can tell me what I *should*
have done! Thanks.
import math
def number_format(num, places=0):
"""Format a number with grouped thousands and given decimal places"""
#is_negative = (num < 0)
#if is_negative:
# num = -num
places = max(0,places)
tmp = "%.*f" % (places, num)
point = tmp.find(".")
integer = (point == -1) and tmp or tmp[oint]
decimal = (point != -1) and tmp[point:] or ""
count = commas = 0
formatted = []
for i in range(len(integer) - 1, 0, -1):
count += 1
formatted.append(integer)
if count % 3 == 0:
formatted.append(",")
integer = "".join(formatted[::-1])
return integer+decimal