0

I have this piece of code:

grams = float(order_weight[2].rstrip("g"))

Which is inside a bsoup function that looks for the grams on one page. The format of the grams is: X,XXX.XX. By that I mean, uses comma for the thousands, and dots for the decimals.

I keep getting errors:

invalid literal for float(): 1,759.33

The number is a example. Is that becuase the comma should be where the dot is and other way around? Can I change it only on this sentence?

Thanks in advance.

Brick Top
  • 85
  • 2
  • 13
  • Your problem is that there are commas at all, not that they are in the wrong place! The solution by @thefourtheye fixes that. – kqr Nov 26 '13 at 12:43
  • Oh, so there shouldn't be any commas for numbers in the thousands? Thanks for the clarification to the answer @kqr – Brick Top Nov 26 '13 at 12:45

2 Answers2

4

You can simply replace the commas with empty string

float(order_weight[2].rstrip("g").replace(',',''))

This was taken from https://stackoverflow.com/a/6633912/1903116. The actual way to deal with this, is to use proper locale

from locale import *
setlocale(LC_NUMERIC, '')
print atof('1,759.33')

Output

1759.33
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2
float(order_weight[2].rstrip("g").replace(",", ""))
greg
  • 1,417
  • 9
  • 28