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

The function should allow for dollar signs, negative signs, and commas.  This 
is what I have so far:

def dollarize(amount):
    negative_sign = 0
    if amount[0] == '$':
        amount = amount[1:]
    elif amount[0] == '-':
        negative_sign = 1
        if amount[1] == '$':
            amount = amount[2:]
        else:
            amount = amount[1:]
    else:
        pass
    amount_list = amount.split(",")
    final_amount = ""
    for x in range(len(amount_list)):
        final_amount = final_amount + amount_list[x]
    dollar_float = float(final_amount)
    dollar_rounded = round(dollar_float,2)
    if negative_sign == 1:
        dollar_string = "-$%.2f" % dollar_rounded
    else:
        dollar_string = "$%.2f" % dollar_rounded
    return dollar_string
    
    
amount = raw_input("Enter an amount: ")
dollar_amount = dollarize(amount)
print dollar_amount   

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?


      
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to