# Python如何使用round()函数？代码示例

2021年3月28日13:46:44 发表评论 801 次浏览

## 本文概述

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.``````

..a)如果仅给出一个整数, 即15, 那么它将四舍五入为15。

..b)如果给出了一个十进制数，那么如果十进制值>=5，它将四舍五入到整数，如果十进制值<5，它将四舍五入到整数下限。

## Python3

``````# for integers
print ( round ( 15 ))

# for floating point
print ( round ( 51.6 ))

print ( round ( 51.5 ))

print ( round ( 51.4 ))``````

``````15
52
52
51``````

## Python3

``````# 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：如果参数中除了数字以外的任何其他数字, 都会引发此错误。

## Python3

``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``````

## Python3

``````# practical application
b = 1 / 3
print (b)
print ( round (b, 2 ))``````

``````0.3333333333333333
0.33``````