Formatting a numerical string w/commas
Timothy Grant
tjg at avalongroup.net
Tue Feb 22 16:55:48 EST 2000
I've seen some traffic on this formatting numbers, and recently had to
format and deformat some number for a Tkinter app I was writing, so I
wrote to fairly generic functions for doing so.
This is the first time I've ever posted *real* code on the list so
please be gentle, but constructive criticism, especially about style, is
always welcome.
############################################################
#
# Name: commanumber()
#
# Purpose: To format a number with commas and possibly a
# dollar sign.
#
# Arguments: n = the number to be converted
# dp = number of decimal places (defaults to 2)
# ds = dollar sign (1|0) (defaults to $)
#
def commanumber(n, dp=2, ds=1):
if not n:
return '' # If None then bail out here
if type(n) == type('x'):
if n == '':
return '' # If an empty string then bail out here.
n = string.atof(n)
m = '%0.*f' % (dp, n)
d = string.split(m, '.') # Split at the decimal point
r = list(d[0])
# It looks ugly but it really isn't. A couple of really nice
Pythonisms
# make it work right. The first is list insertion, and the second is
integer
# division.
#
# the insertion point is calculated based on the counter item, plus
the a left
# shift for each ',' already inserted the ((x/3)-1)
#
for x in range(3, len(r), 3):
r[(x+((x/3)-1))*(-1):(x+((x/3)-1))*(-1)] = [',']
if ds:
s = '$'
else:
s = '' # Rebuild the string from the list
for i in r:
s = s + i
if len(d) == 2: # Check to see if we have a decimal portion to add
return s + '.' + d[1]
else:
return s
############################################################
#
# Name: stripfmt()
#
# Purpose: Strip all formatting from a prettified number
#
# Arguments: n = the number to strip
#
def stripfmt(n):
n = string.replace(n, ',', '') #remove commas
n = string.replace(n, '$', '') #remove dollar signs.
return n
--
Stand Fast,
tjg.
Chief Technology Officer tjg at exceptionalminds.com
Red Hat Certified Engineer www.exceptionalminds.com
Avalon Technology Group, Inc. (503) 246-3630
>>>>>>>>>>>>Linux...Because rebooting isn't normal<<<<<<<<<<<<
More information about the Python-list
mailing list