2024年6月9日发(作者:)
round函数用法
round函数是Python中的一个内置函数,可用于将传入的数字
四舍五入到指定的小数位数。这个函数的用法比较简单,特别适合那
些对编程不是非常熟悉的人,它可以帮助用户简单快捷地实现自己的
算法。
基本语法
round函数的基本语法如下:
round(number [, ndigits])
其中,number是你要进行四舍五入的数字,而ndigits是你要
保留到小数点后几位,如果不提供此参数,则该函数会四舍五入至最
接近的整数。
round函数的实例
下面就来给大家举一些round函数的实例,帮助大家快速掌握它
的用法:
例1:
#!/usr/bin/python3
a = 3.1415
#Round off to 2 decimal places
print(Round off to 2 decimal places : round(a,2))
#Round off to nearest integer
print(Round off to nearest integer : round(a))
输出结果:
- 1 -
Round off to 2 decimal places : 3.14
Round off to nearest integer : 3
从上面的输出结果可以看出,在没有提供ndigits参数时,round
函数将会把3.1415四舍五入至最接近的整数,即3。而在提供ndigits
参数时,round函数则会把3.1415四舍五入至2位小数,即3.14。
例2:
#!/usr/bin/python3
b = 3.75
#Round off to 2 decimal places
print(Round off to 2 decimal places : round(b,2))
#Round off to nearest integer
print(Round off to nearest integer : round(b))
输出结果:
Round off to 2 decimal places : 3.75
Round off to nearest integer : 4
从上面的输出结果可以看出,3.75因为大于它的临近整数3,所
以round函数将它四舍五入到最接近的整数4,而当提供ndigits参
数时,round函数仍然将四舍五入至小数点后2位,即3.75。
round函数的可选参数
除了之前提到的number参数和ndigits参数,round函数还有
另外一个可选参数ndigits参数,它可以用来控制浮点数位数的限定,
也就是说,可以确定在传入参数number中,有多少位浮点数可以四
- 2 -
舍五入到指定的小数位数。
例3:
#!/usr/bin/python3
#Round off to 2 decimal places
c = 3.1415926
print(Round off to 2 decimal places : round(c, 2))
输出结果:
Round off to 2 decimal places : 3.14
从上面的输出结果可以看出,3.1415926因为大于它的临近整数
3,所以round函数将它四舍五入到小数点后2位,即3.14。
以上就是我们今天介绍的round函数用法的全部内容,可以看出,
round函数的用法不难,只要把握好基本语法以及可选参数的使用,
它就可以帮助用户快速实现精确的小数位数四舍五入的操作。
- 3 -


发布评论