深度阅读

How to Convert float to int Python

作者
作者
2023年08月22日
更新时间
10.4 分钟
阅读时间
0
阅读量

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.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。