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'
3
  • Commas should not be there, you need to remove them using the replace() function Commented Apr 24, 2022 at 17:07
  • 1
    this may depend on your LOCALE and need to use a period . Commented Apr 24, 2022 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. Commented Oct 3, 2022 at 18:10

2 Answers 2

3

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)))
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.