How to Convert float to int Python
Published on Aug. 22, 2023, 12:16 p.m.
To convert a float to an integer in Python, you can use the int()
function, which is a built-in function in Python. The int()
function takes a number or a string as input and returns an integer. If the input is a float, the decimal part will be truncated (rounded down) to produce an integer. Here’s an example:
my_float = 3.14
my_int = int(my_float)
print(my_int) # Output: 3
In this example, we define a float my_float
containing the value 3.14
. We use the int()
function to convert the float into an integer called my_int
. The resulting value in my_int
is equivalent to the original value in my_float
, but with the decimal part truncated.
If the float is negative, the int()
function will round towards zero. If you need to round to the nearest integer instead, you can use the round()
function instead of int()
.
In general, converting a float to an integer can be useful when you need to perform integer arithmetic or when passing integer values as arguments to functions that expect integers.