新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:Pythonround()
內(nèi)置函數(shù)round()用于返回浮點(diǎn)數(shù),它是指定位數(shù)的給定十進(jìn)制數(shù)的舍入版本。

**round(number, ndigits)** #where number can be int,float.
round()參數(shù):
接受兩個(gè)參數(shù)。如果默認(rèn)小數(shù)位數(shù)為 0,函數(shù)將返回最近的整數(shù)。
| 參數(shù) | 描述 | 必選/ 可選 |
|---|---|---|
| 數(shù)字 | 要舍入的數(shù)字 | 需要 |
| ndigits | 給定數(shù)字向上舍入的數(shù)字;默認(rèn)為 0 | 可選擇的 |
舍入()返回值
任何整數(shù)值對(duì) ndigits 都有效,即它的值可以是正的、零的或負(fù)的。如果小數(shù)點(diǎn)后的值> =5,則該值將被舍入到+1,否則它將返回該值,直到提到的小數(shù)位數(shù)。
| 投入 | 返回值 | | 如果沒(méi)有給出 ndigits。 | 返回給定數(shù)字的最近整數(shù)。 | | 如果 ndigits | 返回四舍五入到位數(shù)的數(shù)字 |
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:將一個(gè)數(shù)字舍入到給定的小數(shù)位數(shù)
print(round(2.665, 2))
print(round(2.675, 2))
輸出:
2.67
2.67
示例 3:使用自定義對(duì)象舍入()
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 文章標(biāo)題:創(chuàng)新互聯(lián)Python教程:Pythonround()
當(dāng)前網(wǎng)址:http://fisionsoft.com.cn/article/cdhjpho.html


咨詢
建站咨詢
