0

by reference to this post: ValueError: could not convert string to float on heroku

Others suggesting when converting string to int you have to convert it to float first and then use int()

However, it doesn't work for me and I don't know why.

Here is the code and the error message

a = '6,011'
print(int(float(a)))

ValueError: could not convert string to float: '6,011'

a = '6,011'
print(int(a))

ValueError: invalid literal for int() with base 10: '6,011'
Danny Huang
  • 51
  • 1
  • 5
  • Commas should not be there, you need to remove them using the `replace()` function – Anshumaan Mishra Apr 24 '22 at 17:07
  • 1
    this may depend on your LOCALE and need to use a period `.` – ti7 Apr 24 '22 at 17:07
  • The intent of the question was not clear. Converting to `float` first is if the number has a decimal point. Some cultures use `.` as a decimal point and `,` as a thousands separator; others work the other way around. – Karl Knechtel Oct 03 '22 at 18:10

2 Answers2

2

You can use the replace() function to convert commas to dots, that's why float() function fails when converting from string to a float number:

a = '6,011'
a = a.replace(",", ".")
print(int(float(a)))
Cardstdani
  • 4,999
  • 3
  • 12
  • 31
0

You need to replace the commas. Try this:

a = '6,011'
print(int(a.replace(',', '')))

Output:

6011

But if you are treating comma(,) as a decimal and want to get 6 then use this:

a = '6,011'
print(int(float(a.replace(',', '.'))))

Output:

6
Abhyuday Vaish
  • 2,357
  • 5
  • 11
  • 27