Python Convert Float to Complex

Convert Float to Complex Number

To convert float to complex in python, call complex() builtin function with the given floating-point number passed as argument. Or else, we can add imaginary part to the float value, so that the Python Interpreter would typecast it implicitly to complex datatype.

In this tutorial, we will learn how to convert float to complex number, with the above said two methods.

Method 1: Float to Complex using complex()

In this example, we will take a floating-point number in variable a, convert it to complex type value using complex() builtin function, and store it in output variable.

Python Program

#take a float
a = 3.14
print('Input', a, type(a), sep='\n')

#convert float to complex
output = complex(a)
print('\nOutput', output, type(output), sep='\n')
Run

Output

Input
3.14
<class 'float'>

Output
(3.14+0j)
<class 'complex'>

Method 2: Implicit Casting of Float to Complex

We can add 0 imaginary part and Python implicitly promotes the datatype to the higher type, which in this case from float to complex.

Python Program

#take a float
a = 3.14
print('Input', a, type(a), sep='\n')

#convert float to complex
output = a + 0j
print('\nOutput', output, type(output), sep='\n')
Run

Output

Input
3.14
<class 'float'>

Output
(3.14+0j)
<class 'complex'>

Summary

In this tutorial of Python Examples, we learned how to convert value of float datatype to value of complex datatype, with the help of well detailed example programs.