[Tutor] dollarize.py
Martin Walsh
mwalsh at groktech.org
Sat Jun 21 06:02:01 CEST 2008
Christopher Spears wrote:
> I'm working on an exercise from Core Python Programming. I need to create a function that takes a float value and returns the value as string rounded to obtain a financial amount. Basically, the function does this:
>
> dollarize(1234567.8901) returns-> $1,234,567,89
>
> I strip off the symbols, break the string apart, convert it to a float, and then round it. I'm not sure how to add the commas back after the string has been converted to a rounded float value. Any hints?
>
Quick and dirty attempt (and did I mention ugly?) ...
def addcommas(f):
"""
This amounts to reversing everything left
of the decimal, grouping by 3s, joining
with commas, reversing and reassembling.
"""
# assumes type(f) == float
left, right = ('%0.2f' % f).split('.')
rleft = [left[::-1][i:i+3] for i in range(0, len(left), 3)]
return ','.join(rleft)[::-1] + '.' + right
I think you can also accomplish your broader goal with the locale module
(python2.5), though I don't know it very well.
import sys, locale
def dollarize(s):
s = ''.join([n for n in str(s) if n not in ('$', ',')])
if sys.platform == 'win32':
lcl = 'US'
else: # linux and mac?
lcl = 'en_US.UTF8'
locale.setlocale(locale.LC_MONETARY, lcl)
return locale.currency(float(s), 1, 1)
print dollarize(12345678.9999)
# $12,345,679.00
print dollarize('123456780.0999')
# $123,456,780.10
print dollarize('$12345670.9999')
# $12,345,671.00
print dollarize('$12,345,678.123')
# $12,345,678.12
HTH,
Marty
More information about the Tutor
mailing list