新聞中心
這里有您想知道的互聯(lián)網營銷解決方案
創(chuàng)新互聯(lián)Python教程:Pythonround()
內置函數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 當前題目:創(chuàng)新互聯(lián)Python教程:Pythonround()
網站網址:http://www.dlmjj.cn/article/cdhjpho.html


咨詢
建站咨詢
