grouping in module 'locale'
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Sat Jan 26 14:52:26 EST 2008
En Fri, 25 Jan 2008 14:46:13 -0200, Roman Bertle <bertle at smoerz.org>
escribi�:
> I try to format monetary values using the locale module, python2.5:
>>>> locale.localeconv()
> {... 'mon_thousands_sep': ' '
>>>> locale.currency(1234.5678, grouping=True, symbol=False)
> '1234,57'
>
> As you can see, the decimal point is correctly set to ','. But the
> grouping is not done, every 3 digits should be separated by space (' ').
> Using the 'de_DE.utf8' locale, ist works:
>>>> locale.currency(1234.5678, grouping=True, symbol=False)
> '1.234,57'
>
> The difference here is that thounds_sep is '.', not ' '. If we look at
> the code
> of locale.py, revision 55038, lines 157-161, the inserted spaces are
> later
> deleted again:
>
> while seps:
> sp = formatted.find(' ')
> if sp == -1: break
> formatted = formatted[:sp] + formatted[sp+1:]
> seps -= 1
Looks like a bug, please report it at http://bugs.python.org
Only *leading* and *trailing* spaces should be removed, the code above
removes spaces anywhere. This would be a better alternative:
if seps:
i = 0
while seps and i<len(formatted) and formatted[i]==' ':
seps -= 1
i += 1
formatted = formatted[i:]
if seps:
i = len(formatted)-1
while seps and i>=0 and formatted[i]==' ':
seps -= 1
i -= 1
formatted = formatted[:i+1]
Integers should be processed that way too:
py> locale.format('%10d', 1234567, True)
' 1.234.567'
(output has 12 characters, not 10)
Another issue: the code currently assumes that mon_thousands_sep and
thousands_sep are single characters, but they might be longer. There
should be a seps *= len(separator used) before the above whitespace
removal.
I'll try to make a patch tomorrow.
--
Gabriel Genellina
More information about the Python-list
mailing list