To convert a float to an integer in Python, the easiest way is with the int() function. int() will remove the decimal from the floating point number.
f = 1.2345
print(int(f))
#Output:
1
You can also use the math module trunc() function to convert a float variable to an integer.
import math
f = 1.2345
print(math.trunc(f))
#Output:
1
If you want to take into consideration the decimal of the number, you can use round() which will round up or down to the nearest integer.
f = 6.5432
print(round(f))
#Output:
7
When working with variables in programming, the ability to easily be able to convert variables into objects of a different variable type is valuable.
One such case is if you want to convert a float into an integer in Python.
Floats, or floating point numbers, have numbers after the decimal place.
If you want to convert the number into an integer, and remove the decimal portion of the float, the easiest way is with the int() function.
Below is a simple example of how you can use int() to convert a float into an integer in Python.
f = 1.2345
print(int(f))
#Output:
1
Using math Module trunc() to Convert Float to Integer in Python
Another method you can use to convert a float to an integer is with the math module trunc() function.
trunc() removes the decimal from a number and returns just the whole number piece of a number.
Below is a simple example showing you how to use trunc() to change a float to an integer in Python.
import math
f = 1.2345
print(math.trunc(f))
#Output:
1
Using round() to Convert Float to Integer in Python
One last function you can use to convert a float to an integer is with the built-in round() function.
round() will round a float up or down, depending on the decimal, to the nearest integer.
Below is an example of how you can use round() to turn a float into an integer in Python.
f = 6.5432
print(round(f))
#Output:
7
Hopefully this article has been useful for you to learn how to convert a float to an int in Python.