Type conversion of float to int is done by using Using int() function or using math module methods math.floor() and math.ceil().
Example convert float to int Python
Simple example code.
Using int() Function
This method is prone to data loss and hence isn’t recommended.
float_1 = 1.1
float_2 = 1.5
float_3 = 1.9
print(int(float_1))
print(int(float_2))
print(int(float_3))
Output:
Using the math module
You have to import the math module for this example.
math.ceil: returns the smallest integer value that is greater than or equal to the argument.
math.floor: Returns the largest integer less than or equal to the argument.
import math
float_1 = 1.1
float_2 = 2.5
float_3 = 3.9
print(math.floor(float_1))
print(math.ceil(float_1))
print(math.floor(float_2))
print(math.ceil(float_2))
print(math.floor(float_3))
print(math.ceil(float_3))
Output:
2
2
3
3
4
Do comment if you have any doubts and suggestions on this float to int topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.