56. Python round()

发布时间:2023-12-08

Python round()

更新:2022-07-24 11:11 内置函数 round() 用于返回浮点数,它是指定位数的给定十进制数的舍入版本。

round(number, ndigits) # where number can be int, float.

round() 参数:

接受两个参数。如果默认小数位数为 0,函数将返回最近的整数。

参数 描述 必选/ 可选
数字 要舍入的数字 需要
ndigits 给定数字向上舍入的数字;默认为 0 可选择的

round() 返回值

任何整数值对 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