內置函數round()
用於返回浮點數,它是指定位數的給定十進制數的舍入版本。
**round(number, ndigits)** #where number can be int,float.
round()
參數:
接受兩個參數。如果默認小數位數為 0,函數將返回最近的整數。
參數 | 描述 | 必選/ 可選 |
---|---|---|
數字 | 要舍入的數字 | 需要 |
ndigits | 給定數字向上舍入的數字;默認為 0 | 可選擇的 |
舍入()返回值
任何整數值對 ndigits 都有效,即它的值可以是正的、零的或負的。如果小數點後的值> =5,則該值將被舍入到+1,否則它將返回該值,直到提到的小數位數。
| 投入 | 返回值 |
| 如果沒有給出 ndigits。 | 返回給定數字的最近整數。 |
| 如果 ndigits | 返回四捨五入到位數的數字 |
Python 中round()
方法的示例
示例round()
在 Python 中是如何工作的?
# for integers
print(round(10))
# for floating point
print(round(10.7))
# even choice
print(round(5.5))
輸出:
10
11
6
示例 2:將一個數字舍入到給定的小數位數
print(round(2.665, 2))
print(round(2.675, 2))
輸出:
2.67
2.67
示例 3:使用自定義對象舍入()
class Data:
id = 0
def __init__(self, i):
self.id = i
def __round__(self, n):
return round(self.id, n)
d = Data(10.5234)
print(round(d, 2))
print(round(d, 1))
輸出:
10.52
10.5
原創文章,作者:B34ZY,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/127579.html