close

[Solved] ValueError: could not convert string to float

Hello Guys, How are you all? Hope You all Are Fine. Today when I run my code I get the following error in my stack track ValueError: could not convert string to float in Python. So Here I am Explain to you all the possible solutions here.

Without Wasting your time, Lets start This Article to Solve This Error.

How This ValueError: could not convert string to float Occurs ?

I Have Simple code.

content = ["100", "200", "3,464", "400"]

for item in content:
    print(float(item))

When I run my Code it give me Following error.

ValueError: could not convert string to float: '3,64'

How To Solve ValueError: could not convert string to float?

Question: How To Solve ValueError: could not convert string to float?
Answer: To Solve ValueError: could not convert string to float you have to convert string to float value. Your Error is pretty simple. Somewhere in your code where you print float is not convertible to datatype float which means you are giving string to float and that is not convertible. The second solution is You just need to use try and except. So that you don’t have to face error anymore. Just like the below Example.

Solution 1 : Convert String To intiger

Your Error is pretty simple. Somewhere in your code where you print float is not convertible to datatype float which means you are giving string to float and that is not convertible.

Here is Example.

So values like 4,200.42 would be converted to 4200.42 as a float. There you might face ValueError: could not convert string to float. So that all you need to do is just remove ,

from 4,200.42

To 4200.42. Now 4200.42 this will solve your error.

Solution 2 : use try…except

You just need to use try and except. So that you don’t have to face error anymore. Just like the below Example.

content = ["100", "200", "3,464", "400"]

for item in content:
    try:
        print(float(item))
    except:
        print("Given Value is Not convertable")

Here Is Your Output.

100.0
200.0
Given Value is Not convertable
400.0

Solution 3: Remove Space

First of all check if your value contain any space Or not. If your value contain any space then you have to face this error.

Suppose your value is “45” then this code will Run without any error. If you pass value with space like “45 ” then you have to face this error.

So possible solution is to remove space Or replace space.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also Read

Leave a Comment