pythonround怎么⽤_Pythonround()⽤法及代码⽰例
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
python新手代码示例
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)类型转换。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论