tags:

views:

117

answers:

2

Let's say I have a string like that: '12,423,343.93'. How to convert it to float in simple, effective and yet elegant way?

It seems I need to remove redundant commas from the string and then call float(), but I have no good solution for that.

Thanks

+9  A: 
s = "12,423,343.93"
f = float(s.replace(",", ""))
Ned Batchelder
Thanks! I tried .replace() but thought it cannot replace to empty string, so silly...
bocco
Heh, this isn't Oracle, empty string isn't the same as null. :-) You could also replace ' ' with '', as spaces are also sometimes used as thousands-separators.
bobince
+6  A: 

Note that the seperator symbols used vary from country to country. In some cultures, "." is used to seperate groups, and "," indicates a decimal point for instance. If you're parsing user-entered strings like this, it may be better to use the locale module instead. For example:

>>> import locale
>>> locale.atof('12,423,343.93')  # No locale set yet, so this will refuse to parse
ValueError: invalid literal for float(): 12,423,343.93   

>>> locale.setlocale(locale.LC_NUMERIC, "en_GB")  # Use a UK locale.
>>> locale.atof('12,423,343.93')
12423343.93
Brian
I had given you an upvote, now I'm no longer sure. I do like the idea, but today I was suddenly reminded of how little portable locales are. Across three machines, I had to use three different locale names to produce the same result.
krawyoti
Hmm. You may have a point. Just tried out the same on a windows system and indeed locales do seem to be pretty awkward to use. You need to have the exact locale (including charset, even though it's not needed for the numeric processing) installed to be able to set it.
Brian