askvity

How do you convert a float to an int in Python?

Published in Python Conversion 2 mins read

You can convert a float to an integer in Python using the int() function.

The int() function truncates the decimal part of the float, effectively rounding it down to the nearest whole number.

Here's how it works:

float_number = 3.14
integer_number = int(float_number)
print(integer_number)  # Output: 3

float_number = 7.99
integer_number = int(float_number)
print(integer_number)  # Output: 7

float_number = -2.5
integer_number = int(float_number)
print(integer_number)  # Output: -2

Explanation:

  • The int() function takes the float as an argument.
  • It returns the integer part of the float, discarding any fractional part. Note that it does not round to the nearest integer. It truncates.
  • If the float is negative, it truncates towards zero (e.g., -2.5 becomes -2).

Important Considerations:

  • Data Loss: Converting a float to an int results in data loss, as the decimal portion is discarded. If you need to round the float to the nearest integer, you should use the round() function instead.

    float_number = 3.7
    rounded_number = round(float_number)
    print(rounded_number) # Output: 4
  • Error Handling: While int() can handle basic float-to-int conversions, if you're dealing with strings that represent floating-point numbers, you may need to convert them to floats first before converting them to integers. Be prepared to handle potential ValueError exceptions if the string cannot be converted.

    string_number = "3.14"
    try:
        float_value = float(string_number)
        integer_value = int(float_value)
        print(integer_value)  # Output: 3
    except ValueError:
        print("Invalid input: Cannot convert string to integer")

In summary, the int() function is a straightforward way to convert a float to an integer by truncating the decimal portion.

Related Articles