printing float as formatted dollars
Tim
nospam-trice at comcast-nospam.net
Tue May 11 02:55:42 EDT 2004
"Peter Hansen" <peter at engcorp.com> wrote in message
news:V72dncRoWf6o7gbdRVn-gw at powergate.ca...
> Tim wrote:
>
> > "Larry Bates" <lbates at swamisoft.com> wrote in message
> > news:YtqdnZOyj_KSfArdRVn_iw at comcast.com...
> >
> >>Here is a function I wrote and use. Note: floats
> >>have rounding "issues" when they get very large.
> [snip long code]
> >>
> > Thanks for the code!, it was a big help. I had started trying to piece
> > together some logic (below), but I know there are holes in it (negative
> > numbers, for one).
> [snip also long code]
>
> I still find this one much easier to swallow (from the
> aforementioned other thread).
>
> >>> import re
> >>> s = 1234567.89
> >>> '$' + re.sub(r'(?<=\d)(?=(\d\d\d)+(\.|$))', ',', str(s))
> '$1,234,567.89'
>
> -Peter
I agree. This is a very concise solution. Since I'm new to both Python and
regular expressions, it took some follow-up reading to understand how/why
this works. So, I guess in addition to a solution you could say that it
also led me to a basic understanding of regular expressions which seems well
worth having (and which I otherwise probably would have regretfully
continued to ignore).
I appreciate your help,
Tim
More information about the Python-list
mailing list