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.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
gregturn
  • 2,625
  • 3
  • 25
  • 40

4 Answers4

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.

Rob
  • 7,377
  • 7
  • 36
  • 38
3

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

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • +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 Apr 30 '09 at 16:37
  • You're right, this is for parsing an invoice to get a monetary amount. – gregturn Apr 30 '09 at 16:41
  • 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 Apr 30 '09 at 16:51
3

You could strip the commas:

txt = txt.replace(',', '')
value = float(txt)
thesamet
  • 6,382
  • 2
  • 31
  • 42
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.

Community
  • 1
  • 1
Joe Holloway
  • 28,320
  • 15
  • 82
  • 92