Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

You could strip the commas:

txt = txt.replace(',', '')
value = float(txt)

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top