Python中round()函数的基本用法

在Python中,可以使用内置的round()函数来对float类型的数据进行四舍五入。round()函数的基本用法如下:
round(number[, ndigits])
其中,number表示要进行四舍五入的数字,ndigits表示要保留的小数位数,可以省略,默认为0。如果ndigits为正数,则表示保留小数点后ndigits位,如果ndigits为负数,则表示保留小数点前ndigits位。下面是一些示例代码:
a = 3.1415926
b = round(a, 2)  # 保留2位小数
print(b)  # 输出3.14
 c = round(a)  # 不指定ndigits,默认保留0位小数
print(c)  # 输出3
 d = round(a, -1)  # 保留1位小数点前的数字
print(d)  # 输出0
需要注意的是,round()函数在四舍五入时可能会存在精度误差的问题,因此在处理精度要求较高的数据时需要谨慎使用。

猜你喜欢

转载自blog.csdn.net/weixin_49786960/article/details/131130790