An Interest In:
Web News this Week
- May 1, 2024
- April 30, 2024
- April 29, 2024
- April 28, 2024
- April 27, 2024
- April 26, 2024
- April 25, 2024
Converting String to Float in Python
In this short tutorial, we look at how we can convert a string object into a floating object, we look at different methods and we discuss the limitation as well.
This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.
Table of Content
- Why would you need to convert a String to Float in Python?
- Solution: Using the float() function
- Limitation and Caveats
Why would you need to convert a String to Float in Python?
Changing data types in python is a common practice, and python has provided us with functions to facilitate this. However, one frequently looked up method is converting a string to float. The most common places where you would come across this is while reading and working with files. In such cases, you would need to convert numerical values from a string into float/ int before you can use any operations.
Similar to the above example you would come across similar instances where you would need to convert a string to float in python.
Solution: Using the float() function
In this solution we use the most common method to convert any data type including a string to float in python; float()
.
Syntax of float():
float(x)
Parameter
Here x
can be an int or a string. It could contain signs, this would not affect the value returned.
Code and Explanation:
f1 = float("123.123")//output: 123.123f2 = float("1")//output: 1.0f3 = float(1)//output: 1.0print(type(f1))
As you can see the above strings were converted into a floating object. The only thing you should keep in mind is that the string should contain a numerical decimal or integer value, only then would the float function be able to convert the string to float.
To check the data types you can use the type()
function before and after using the float()
. This function returns the data type of the object.
Similar to float()
, values of other data types can be converted into integers and strings using the Int()
, str()
.
f1 = int("1")//output: 1f2 = int(12.3)//output: 12f3 = str(123)//output: "123"f4 = str(12.3)//output: "12.3"
Limitations and Caveats
- As mentioned earlier, the string should contain a float value else
float()
would returnValueError
- If the number outside the range of a floating variable it would return
OverflowError
- And lastly if the no value is passed as an argument it returns 0.0
Original Link: https://dev.to/hrishikesh1990/converting-string-to-float-in-python-47mm
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To