当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Float转Int用法及代码示例


将 float 值转换为 int 是通过类型转换完成的,这是一种将操作数转换为特定类型的显式方法。然而,需要注意的是,这种类型的转换可能往往是有损的(数据丢失)。将像 2 这样的 int 值转换为浮点数将导致 2.0,这种类型的转换是安全的,因为不会丢失数据,但是将 3.4 转换为 int 值将导致 3 导致有损转换。例子:

Input: 3.3 
Output:3 

Input: 5.99
Output:5

方法一:使用int()转换:

要将浮点值转换为 int,我们使用 内置 int() 函数,该函数修剪小数点后的值并仅返回整数/整数部分。

用法: int(x) 

返回:整数值

范例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__)

输出:

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

方法二:使用 math.floor() 和 math.ceil() 进行转换。

可以使用 math.floor() 函数将浮点值转换为不大于输入的 int 值,也可以使用 math.ceil() 函数将其转换为大于输入的最小整数的 int 值。为了使用这些方法,要导入数学模块。

用法: math.floor(x)

参数:

x:这是一个数值表达式。

返回值:不大于 x 的最大整数。

用法: math.ceil(x)

参数:

x:这是一个数值表达式。

返回值:不小于 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

相关用法


注:本文由纯净天空筛选整理自sooryanath大神的英文原创作品 How to convert Float to Int in Python?。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。