As I mentioned in my previous post, if you are doing any arithmetic operations and if you have any floating number, Python automatically converts an integer to a floating number. To convert any type number to another type, we simply write representative code before the number. In this article, you will learn how to convert numbers in between.
Prerequisites:
2- Integers
5- Operaters
Code:
>>>a = 12
>>>print(type(a))
>>># to make a comment in python you can use # at the beginning
>>># here I am converting variable a to a float number.
>>>a = float(a)
>>>print(a)
>>>print(type(a))
>>># here I am converting variable a to a complex number.
>>>a = complex(a)
>>>print(a)
>>>print(type(a))
Output:
<class 'int'>
12.0
<class 'float'>
(12+0j)
<class 'complex'>
Python, can't convert complex to integer. Not this way at least. When converting from floating to integer, Python will remove decimals.
Code:
>>>a = 12.453463463
>>>print(type(a))
# below I am converting variable a to a integer number.
>>>a = int(a)
>>>print(a)
>>>print(type(a))
Output:
<class 'float'>
12
<class 'int'>
First, we see that the number is float and then we convert it to an integer and we print it.