[Tutor] Python 3: string to decimal conversion

Alan Gauld alan.gauld at yahoo.co.uk
Mon May 23 05:39:17 EDT 2016


On 23/05/16 02:45, US wrote:

> I tried the float() function instead of decimal.Decimal and got an
> error message: could not convert string to float: '($75.59)'.

The problem is that the functions don;t recognize the parens as a
negative sign. You will need to convert them yourself. I suggest you
write a function that takes a string and if it starts with parens then
strip them off and prepend a negative sign, otherwise return the
original. You will also need to get rid of the $ sign...
Something like:

def normalizeValue(val):
    if amt.startswith('(') and amt.endswith(')'):
       amt = '-' + amt[1:-1]
    return amt.replace('$','')

Then call that when you try to convert to Decimal


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list