Convert String to Float in Python

ItsMyCode |

In this tutorial, we will take a look at how to convert string to float in Python.

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.

float() function

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.

Example 1 – Convert string to float

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'>

Example 2 – Default float conversion without any input parameter

output = float()
print(output)

# Output
# 0.0

Example 3 – Convert a String representing integer to a floating-point number

# 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'>

Example 4 – Converting string only with a decimal part to 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'>

Example 5 – Converting a string of exponential to 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