如何在Python中将 Float 转换为 Int?
将float值转换为int是通过Type conversion完成的,这是一种将操作数转换为特定类型的显式方法。然而,需要注意的是,这种类型的转换可能往往是有损的(数据丢失)。将像2这样的 int 值转换为浮点数将导致2.0 ,这种类型的转换是安全的,因为不会丢失数据,但是将3.4转换为 int 值将导致3导致有损转换。
例子:
Input: 3.3
Output: 3
Input: 5.99
Output: 5
方法 1:使用int()进行转换:
要将浮点值转换为 int,我们使用内置的 int()函数,该函数修剪小数点后的值并仅返回整数/整数部分。
Syntax: int(x)
Return: integer value
示例 1:将float类型的数字转换为int类型的结果。
Python3
# conversion from float to int
num = 9.3
# printing data type of 'num'
print('type:',
type(num).__name__)
# conversion to int
num = int(num)
# printing data type of 'num'
print('converted value:', num,
', type:', type(num).__name__)
Python3
# example of unpredictable
# behaviour of int()
num1 = 5.9
num2 = 5.99999999999999999999
num1 = int(num1)
num2 = int(num2)
print(num1, num2, sep = '\n')
Python3
# conversion using floor and ceil .
# importing math module
import math
num = 5.6
floor_value = math.floor(num)
ceil_value = math.ceil(num)
print("the result using floor() : ",
floor_value ,
', type : ',type(floor_value).__name__)
print("the result using ceil() : ",
ceil_value,
', type: ', type(ceil_value).__name__)
输出:
type: float
converted value: 9 , type: int
示例 2:在大多数情况下,int()函数将结果四舍五入为小于或等于输入的整数,但其行为既不明确也不可预测。一个这样的例子如下所示。
Python3
# example of unpredictable
# behaviour of int()
num1 = 5.9
num2 = 5.99999999999999999999
num1 = int(num1)
num2 = int(num2)
print(num1, num2, sep = '\n')
输出:
5
6
方法 2:使用math.floor()和math.ceil()进行转换。
可以使用 math.floor()函数将浮点值转换为不大于输入的 int 值,也可以使用 math.ceil() 将其转换为大于输入的最小整数的 int 值函数。为了使用这些方法,要导入数学模块。
Syntax: math.floor(x)
Parameter:
x: This is a numeric expression.
Returns: largest integer not greater than x.
Syntax: math.ceil(x)
Parameter:
x: This is a numeric expression.
Returns: Smallest integer not less than x.
示例:在下面的示例中,使用 floor() 和 ceil() 方法实现了从 float 到 int 的转换,前者返回不大于输入的 int,后者返回大于输入的最小整数。
Python3
# conversion using floor and ceil .
# importing math module
import math
num = 5.6
floor_value = math.floor(num)
ceil_value = math.ceil(num)
print("the result using floor() : ",
floor_value ,
', type : ',type(floor_value).__name__)
print("the result using ceil() : ",
ceil_value,
', type: ', type(ceil_value).__name__)
输出:
the result using floor() : 5 , type : int
the result using ceil() : 6 , type: int