python round()

时间:2020-02-23 14:43:15  来源:igfitidea点击:

Python round()函数用于对数字进行舍入运算。

python round()

Python round()函数语法为:

round(number[, ndigits])

小数点后的数字四舍五入为n位精度。

如果未提供ndigit或者为None,则返回最接近的整数。

将输入数字四舍五入为整数时,如果四舍五入值和四舍五入值均相等,则返回偶数。
例如,将10.5舍入为10,而将11.5舍入为12。

任何整数值都对n位数字有效(正数,零或者负数)。

Python round()函数示例

让我们看一下round()函数的示例。

round()转换为整数

print(round(10, 2))

print(round(10.2))
print(round(10.8))
print(round(11.5))

输出:

10
10
11
12

将round()整齐

# if both side of rounding is same, even is returned
print(round(10.5))
print(round(12.5))

输出:

10
12

round(),ndigit为无

print(round(1.5))
# OR
print(round(1.5, None))

输出:

2
2

负ndigit的round()

print(round(100, 0))
print(round(100.1234, -4))
print(round(100.1234, -5))

输出:

100
100.0
0.0

Python圆形浮点数

将四舍五入到浮点数上时,结果有时会令人惊讶。
这是因为数字以二进制格式存储,并且大多数十进制小数不能完全表示为二进制小数。

Python会进行近似并为我们提供四舍五入的值,因为这种浮点算法有时会产生令人惊讶的值。

例如:

>>>.1 + .1 == .2
True
>>>.1 + .1 + .1 == .3
False
>>>.1 + .1 + .1 + .1 == .4
True

我们来看一些带浮点数的round()函数的示例。

print(round(2.675, 2))

print(round(1.2356, 2))
print(round(-1.2356, 2))

输出:

2.67
1.24
-1.24

请注意,第一次浮点舍入似乎是错误的。
理想情况下,它应四舍五入为2.68。

这是浮点数算术运算的局限性,在处理浮点数时我们不应该依赖条件逻辑。

round()与自定义对象

如果它们实现__round __()函数,我们也可以对自定义对象使用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