如何在 Python 中將浮點數轉換為整數?
在 Python 中,有兩種數字資料型別:整數和浮點數。一般來說,整數沒有小數點,基值為 10(即十進位制)。而浮點數則有小數點。Python 提供了一些內建方法來將浮點數轉換為整數。在本文中,我們將討論其中的一些方法。
使用 int() 函式
int() 函式透過去除小數點並只保留整數部分來將浮點數轉換為整數。此外,int() 函式不會像 49.8 向上舍入到 50 那樣對浮點值進行舍入。
示例
在這個示例中,小數點後的資料被刪除,我們只有整數(整數)。
num = 39.98
print('Data type of num:', type(num).__name__)
# float to int conversion
num = int(num)
print('Converted value and its data type:', num,', type:', type(num).__name__)
輸出
Data type of num: float Converted value and its data type: 39 , type: int
示例
int() 函式接受整數字符串或浮點數,但它不接受浮點數字符串。如果給定浮點數字符串,則首先需要使用 float() 函式將其轉換為浮點數,然後將其應用於 int()。否則,它將引發 ValueError。
num = '1.5'
print('Data type of num:', type(num).__name__)
# float to int conversion
num = int(num)
print('Converted value and its data type:', num,', type:', type(num).__name__)
輸出
Data type of num: str Traceback (most recent call last): File "/home/cg/root/67537/main.py", line 6, innum = int(num) ValueError: invalid literal for int() with base 10: '1.5'
示例
在某些情況下,int() 函式的行為不可預測,對於一些輸入浮點值,它可能會將結果舍入到小於或等於輸入浮點值的整數。
num = '1.5'
print('Data type of num:', type(num).__name__)
# float to int conversion
num = int(float(num))
print('Converted value and its data type:', num,', type:', type(num).__name__)
輸出
Data type of num: str Converted value and its data type: 1 , type: int
示例
在這個示例中,int() 函式將浮點值舍入到下一個整數。
num = 1.9999999999999999
print('Data type of num:', type(num).__name__)
# float to int conversion
num = int(num)
print('Converted value and its data type:', num,', type:', type(num).__name__)
輸出
Data type of num: float Converted value and its data type: 2 , type: int
使用 math 模組的截斷函式
使用 math 模組中的截斷函式trunc(),我們可以將浮點數轉換為整數。
示例
從這個示例中,我們成功地使用 math.trunc() 函式將浮點數轉換為整數,其工作原理類似於 int() 函式。我們還可以使用 math.ceil()、math.floor() 和 numpy 庫中的 ndarray..astype(int) 方法來將浮點數轉換為 Python 中的整數資料型別。
from math import trunc
num = 7.12
print('Data type of num:', type(num).__name__)
# float to int conversion
num = trunc(num)
print('Converted value and its data type:', num,', type:', type(num).__name__)
輸出
Data type of num: float Converted value and its data type: 7 , type: int
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP