Python round()函数的使用(精度)


round(number[, ndigits])

    Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

    For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as number.

    For a general Python object number, round delegates to number.__round__.

    Note

    The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

round()函数返回的是一个精确到ndigits的浮点数

>>> print(round(80.23456,2))
80.23

如果省略ndigits或者为None,则返回其输入的最接近的整数。

>>> print(round(80.23456))
80

对于支持round()的内置类型,值被精确到最接近的(10)^(-ndigits)

>>> print(round(6,-1))
10
>>> print(round(80,-2))
100
>>> print(round(4,-1))
0

 

如果两个倍数相等,则向均匀选择进行舍入(例如,round(0.5)和round(-0.5)均为0,round(1.5)为2。

>>> print(round(1.6))
2
>>> print(round(1.4))
1
>>> print(round(0.5))
0
>>> print(round(-0.5))
0

任何整数值对ndigits(正数,零或负数)有效。

>>> print(round(8,-1))
10
>>> print(round(4,-1))
0

如果省略ndigits或None,则返回值为整数。 否则返回值与数字的类型相同。



对于一般的Python对象编号,将代理舍入为.__ round__。

 

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值