1

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.

4 Answers 4

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

This works the easiest, considering I don't have the locale module. Thanks!
3

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

3 Comments

+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. stackoverflow.com/questions/723356/…
You're right, this is for parsing an invoice to get a monetary amount.
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.
3

You could strip the commas:

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.