A suggestion for a possible Python module
mgerrans at mindspring.com
Sun Mar 9 22:38:34 CET 2003
> > For this one, I'd prefer locale.format().
> Jp Calderone
> > This is the most common alternative solution I hear, and I don't
> > think it's right.
> I agree. My spec was to put commas into numbers, with an
> example which implied it was using the US convention. Eg, it could
> be that the input goes to a program which isn't format aware, so
> it *must* be in that form.
Yes, I must admit, I have a little commas-adding module I often use that has
one method which uses locale and the other which looks like this:
Returns x in the form of a string, with comma formatting.
eg: 123456789 -> 123,456,789
This is my old implementation (commas(), which uses the locale module is
the new fangled technology), which figures out where to put the commas
if type(x) != type(0L):
x = long(x)
if abs(x) < 1000:
return "%d" % x
chunks = 
neg = 0
if x < 0:
neg = 1
x = -x
while x > 999:
chunks.append( x - (x / 1000) * 1000 )
x = x / 1000
s = "-%d" % chunks
s = "%d" % chunks
for i in chunks[1:]:
s = s + ",%03d" % i
I guess it needs to be enhanced for floating point values...
More information about the Python-list