Python round() 函数用于将给定的浮点数四舍五入到最接近的整数值。舍入以指定的小数位数完成。如果未指定要舍入的小数位数,它将舍入到最接近的整数,即 0。
例如,如果您想四舍五入一个数字,比如 6.5。它将被舍入到最接近的整数,即 7。但是,数字 6.86 将四舍五入到小数点后一位,得到数字 6.9。
语法
以下是 Python round() 函数的语法 -
round(x[,n])
参数
- x − 这是要四舍五入的数字。
- n (可选) − 这是给定数字将四舍五入到的小数点数。默认值为 0。
返回值
此函数返回从小数点四舍五入到指定数字的数字。
例以下示例显示了 Python round() 函数的用法。这里,要四舍五入的数字和数字将四舍五入的小数位数作为参数传递给 round() 函数。
print ("round(80.23456, 2) : ", round(80.23456, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))
当我们运行上述程序时,它会产生以下结果——
round(80.23456, 2) : 80.23
round(100.000056, 3) : 100.0
round(100.000056, 3) : 100.0
例
在这里,给定数字将四舍五入的小数位数不存在。因此,采用其默认值 0。
# Creating the number
num = 98.65787
res = round(num)
# printing the result
print ("The rounded number is:",res)
在执行上述代码时,我们得到以下输出 -
The rounded number is: 99
例
如果我们传递一个负数作为参数,则此函数将返回一个负数 closest 。
在此示例中,将创建值为 '-783.8934771743767623' 的对象 'num'。给定值将四舍五入的小数点为 '6'。然后使用 round() 函数来检索结果。
# Creating the number
num = -783.8934771743767623
decimalPoints = 6
res = round(num, decimalPoints)
# printing the result
print ("The rounded number is:",res)
以下是上述代码的输出 -
The rounded number is: -783.893477
例
在下面给出的示例中,创建了一个数组。为了在 Python 中对数组进行舍入,我们使用了 numpy 模块。然后,这个数组作为参数传递给 round() 函数,其中包含 4 个要四舍五入的小数点。
import numpy as np
# the arrray
array = [7.43458934, -8.2347985, 0.35658789, -4.557778, 6.86712, -9.213698]
res = np.round(array, 4)
print('The rounded array is:', res)
上述代码的输出如下 -
The rounded array is: [ 7.4346 -8.2348 0.3566 -4.5578 6.8671 -9.2137]