15
Convert String to Float in Python
ItsMyCode |
In this tutorial, we will take a look at how to convert string to float in Python.
Usually, in Python, the user input that we get will be a string when you read the data from the terminal, excel, CSV, or from a web form. We need to convert the string explicitly into the floating-point value before performing any arithmetic operations. Otherwise, Python will throw valueerror.
The float()
function is a built-in utility method which takes any object as an input parameter and converts into floating point number.Internally float()
function calls specified object__float__ ()
function.
Syntax: float(obj)
The float method accepts only one parameter, which is optional. If you don’t pass any parameter, then the method will return 0.0 as output.
input= "33.455"
print(input)
print('Before conversion',type(input))
# converting string to float
output = float(input)
print(output)
print('After conversion',type(output))
Output
33.455
Before conversion <class 'str'>
33.455
After conversion <class 'float'>
output = float()
print(output)
# Output
# 0.0
# string with integer to float
input= "100"
print(input)
print('Before conversion',type(input))
# converting string to float
output = float(input)
print(output)
print('After conversion',type(output))
Output
100
Before conversion <class 'str'>
100.0
After conversion <class 'float'>
# string with integer to float
input= ".000123"
print(input)
print('Before conversion',type(input))
# converting string to float
output = float(input)
print(output)
print('After conversion',type(output))
Output
.000123
Before conversion <class 'str'>
0.000123
After conversion <class 'float'>
# string with integer to float
input= "1.23e-4"
print(input)
print('Before conversion',type(input))
# converting string to float
output = float(input)
print(output)
print('After conversion',type(output))
Output
1.23e-4
Before conversion <class 'str'>
0.000123
After conversion <class 'float'>
The post Convert String to Float in Python appeared first on ItsMyCode.
15