Tutorial Study Image

Python round()

内置函数 round() 用于返回一个浮点数,该浮点数是给定小数按指定位数四舍五入后的结果。


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

round() 参数

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

参数 描述 必填 /  可选
number  要四舍五入的数字 必需
ndigits  给定数字四舍五入到的位数;默认为 0 可选

round() 返回值

ndigits 的任何整数值都有效,即其值可以为正、零或负。如果小数点后的值 >=5,则该值将四舍五入到 +1,否则它会按所提到的小数位数返回原值。

输入 返回值
 如果未给出 ndigits。  返回与给定数字最接近的整数。
如果给定 ndigits 返回四舍五入到 ndigits 位数的数字

Python 中 round() 方法的示例

示例 1: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:round() 与自定义对象


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