python round怎么用_Python round()用法及代码示例

Python提供了一个内置函数round(),该函数会四舍五入为给定的位数,并返回浮点数,如果没有提供四舍五入的位数,则会将数字四舍五入为最接近的整数。

用法:

round(number, number of digits)

round()参数:

..1) number - number to be rounded

..2) number of digits (Optional) - number of digits

up to which the given number is to be rounded.

如果缺少第二个参数,则round()函数将返回:..a)如果仅给出一个整数,即15,则将四舍五入为15。.b)如果给出一个十进制数,则将四舍五入如果十进制值> = 5,则返回ceil整数;如果十进制<5,则四舍五入为底整数。

如果缺少第二个参数,则下面是round()函数的python实现。

# for integers

print(round(15))

# for floating point

print(round(51.6))

print(round(51.5))

print(round(51.4))

输出:

15

52

52

51

当第二个参数存在时,它返回:当第(ndigit + 1)位数字> = 5时,将四舍五入到的最后一个十进制数字加1,否则保持不变。

如果存在第二个参数,则下面是round()函数的python实现

# when the (ndigit+1)th digit is =5

print(round(2.665, 2))

# when the (ndigit+1)th digit is >=5

print(round(2.676, 2))

# when the (ndigit+1)th digit is <5

print(round(2.673, 2))

输出:

2.67

2.68

2.67

错误与异常

TypeError:如果参数中除了数字以外的任何其他数字,都会引发此错误。

print(round("a", 2))

输出:

Runtime Errors:

Traceback (most recent call last):

File "/home/ccdcfc451ab046030492e0e758d42461.py", line 1, in

print(round("a", 2))

TypeError:type str doesn't define __round__ method

实际应用:

函数舍入的常见用途之一是处理分数和小数之间的不匹配

舍入数字的一种用法是将1/3转换为十进制时,将所有三个都缩短到小数点右边。在大多数情况下,当您需要使用小数点1/3时,将使用四舍五入的数字0.33或0.333。实际上,当与小数点后的小数位数完全不相等时,通常只使用小数点右边的两位或三位数。您如何以小数点显示1/6?记住要四舍五入!

# practical application

b = 1/3

print(b)

print(round(b, 2))

输出:

0.3333333333333333

0.33

注意:在python中,如果我们不给第二个参数就将数字四舍五入到floor或ceil,它将返回例如15.0,而在Python 3中则返回15,因此为了避免这种情况,我们可以在python中使用(int)类型转换。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值