📜  Python round()

📅  最后修改于: 2020-09-20 04:30:14             🧑  作者: Mango

round() 函数将浮点数舍入为指定的小数位数。

round() 函数的语法为:

round(number, ndigits)

round()参数

round() 函数采用两个参数:

  1. 数字-要四舍五入的数字
  2. ndigits(可选)-给定数字四舍五入到的数字;默认为0

从round()返回值

  1. 如果未提供ndigits ,则round()返回最接近给定数字的整数。
  2. 如果给出ndigitsround()返回四舍五入为ndigits位数的数字。

示例1:round()在Python如何工作?

# for integers
print(round(10))

# for floating point
print(round(10.7))

# even choice
print(round(5.5))

输出

10
11
6

示例2:将数字四舍五入到给定的小数位数

print(round(2.665, 2))
print(round(2.675, 2))

输出

2.67
2.67

如果您需要这种精度,请考虑使用为浮点运算设计的decimal模块:

from decimal import Decimal

# normal float
num = 2.675
print(round(num, 2))

# using decimal.Decimal (passed float as string for precision)
num = Decimal('2.675')
print(round(num, 2))

输出

2.67
2.68