新睿云

> 知识库 > Python中round函数真的就是“四舍五入”吗?

Python中round函数真的就是“四舍五入”吗?

作者/来源:新睿云小编 发布时间:2019-12-18

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

以下是 round() 方法的语法:

round( x , n] )

x -- 数字表达式。

n -- 表示从小数点位数,其中 x 需要四舍五入,默认值为0

注意:第二个参数n是可以舍弃的

使用示例:

1.没有参数n的情况

此时虽然没有填写参数n,不过其默认为0,所有填入数字输出均为整数。

# for integers

print(round(15))

 # for floating point

print(round(51.6)) 

print(round(51.5)) 

print(round(51.4))

输出:

15

52

52

51

2.当有参数n的时候

此时小数保留位数按照其参数结果来

注意:保留的结果是按照四舍五入的规律来的

# 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

3.错误与异常

TypeError:如果数字中没有数字,则会引发此错误 参数。

4.某些版本中round也并不是一定是“四舍五入”

print(round("a", 2)) 

python3.5.2该函数对于返回的浮点数并不是按照四舍五入的规则来计算,而会收到计算机表示精度的影响。

round(2.355, 2)

输出:

2.35

5.python2中与python3中round的区别

$ python 

Python 2.7.8 (default, Jun 18 2015, 18:54:19) 

[GCC 4.9.1] on linux2 

Type "help", "copyright", "credits" or "license" for more information. 

>>> round(0.5)

输出:

1.0

$ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) 

[GCC 4.8.4] on linux 

Type "help", "copyright", "credits" or "license" for more information. 

>>> round(0.5)

输出:

0

6.总结:

除非对精确度没什么要求,否则尽量避开用round()函数。近似计算我们还有其他的选择:

使用math模块中的一些函数,比如math.ceiling(天花板除法)。

python自带整除,python2中是/,3中是//,还有div函数。

字符串格式化可以做截断使用,例如 "%.2f" % value(保留两位小数并变成字符串……如果还想用浮点数请披上float()的外衣)。

当然,对浮点数精度要求如果很高的话,请用嘚瑟馍,不对不对,请用decimal模块。

热门标签
new year
在线咨询
咨询热线 400-1515-720
投诉与建议
{{item.description}}

—您的烦恼我们已经收到—

我们会将处理结果发送至您的手机

请耐心等待