views:

304

answers:

4

How can I parse a float scanned from a sheet as text, containing commas?

txt = "1,903.44"
value = float(txt) # This fails due to ',' in string

UPDATE: Sorry I wasn't clear. I'm using jython 2.5, which doesn't have the locale module.

+3  A: 
txt = "1,903.44"
value = float(txt.replace(',', ''))

If you need localization, this won't really work but it does the trick if you know that commas are your separators.

Rob
This works the easiest, considering I don't have the locale module. Thanks!
gregturn
+2  A: 

Use locale.atof() after locale.setlocale(locale.LC_ALL, '').

Mark Ransom
+1 Just wanted to add that if the OP is dealing with monetary values, it may be wiser to use the decimal package instead of floating points. http://stackoverflow.com/questions/723356/when-is-it-appropriate-to-use-floating-precision-data-types
Joe Holloway
You're right, this is for parsing an invoice to get a monetary amount.
gregturn
You can use locale.localeconv()['thousands_sep'] to get the separator character for a locale-safe version of the replace idea. Except in Jython, apparently.
Mark Ransom
+3  A: 

You could strip the commas:

txt = txt.replace(',', '')
value = float(txt)
thesamet
A: 

I would personally use the decimal package when dealing with monetary values to avoid well-documented pitfalls that occur when using floating points.

from decimal import Decimal
txt = txt.replace (',', '')
value = Decimal(txt)

As noted by other posters, this only works if your locale is known to use ',' as thousands separator, but should get you going in the right direction.

Joe Holloway