# locale and number formatting.

Joe Goldthwaite joe at goldthwaites.com
Tue Aug 3 20:59:16 CEST 2010

```I've been working with some developers on a project.  Our standard number
formatting for the entire web site is comma separated with no decimals.
Currency is formatted with the dollar sign.  This is basically how they did
it;

import locale

def currency(value):

return locale.currency(value, grouping=True)

def formatnumber(value):

value = locale.currency(value, grouping=True)

value = value.replace('\$','');

try:

value = value[:-3];

except:

value = value;

return value;

The "formatnumber" function looks awkward.  I'm not even sure what exactly
they're trying to accomplish.  They're stripping off the last three
characters but since the number is formatted by the currency function, it
might have parenthesis. I don't see this working correctly with negative
numbers.

That got me looking in to the locale module again.  I'm having trouble
understanding some of the python documentation on the subject.  I've
searched the web and even searched through all my safaribooksonline to see
if I could get more information on how to improve the code but I'm just not
getting it.

Lets take the first step;

def currency(value):

return locale.currency(value, grouping=True)

This is pretty simple.  My problem is that I want all my currency numbers
formatted with zero decimal places.  There doesn't seem to be an option to
round the value down. I thought that maybe I could change the 'frac_digits'
setting to zero but I can't seem to find a way to change it.

I've found a number of different functions that accomplish this but they're
written from scratch.  I'd really like to use a standard library function to
do it if possible.

With the 'formatnumber" function could be replaced with;

def formatnumber(value):

return locale.format('%0.0f', value, 1)

This inserts the commas and rounds off the decimals.  It doesn't handle
putting parens around the negative numbers.

Is there a better way to do this?  I tried looking up the options for
local.format_string which seems to allow custom "C" formatting but I
couldn't find any examples of what the custom "C" formatting would look
like.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100803/7d40176a/attachment.html>
```