將 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
相關用法
- Python String轉Float用法及代碼示例
- Python exponential轉float用法及代碼示例
- Python float轉exponential用法及代碼示例
- Python Bytes轉Int用法及代碼示例
- Python Int轉Bytes用法及代碼示例
- Python int轉exponential用法及代碼示例
- Pandas DataFrame Float轉Datetime用法及代碼示例
- Python float()用法及代碼示例
注:本文由純淨天空篩選整理自sooryanath大神的英文原創作品 How to convert Float to Int in Python?。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。