首页Python【Python内置函数】r...

【Python内置函数】round()函数

Python 提供了许多内置函数,这些函数是Python语言的一部分,可以直接在Python程序中使用而无需导入任何模块。

本系列将会陆续整理分享一些的Python内置函数。

文章配套代码获取有以下两种途径:
  • 通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj 提取码:mnsj
  • 前往GitHub获取
https://github.com/returu/Python_built-in_functions





01
简介

round() 函数是 Python 中的一个内置函数,用于将数字四舍五入到指定的精度。

round() 函数的基本语法如下:

round(number, ndigits=None)
参数说明:
  • number:要进行四舍五入的数字;
  • ndigits:可选参数,要保留的小数位数。

返回值:

round() 函数返回四舍五入后的数字,类型与输入的 number 相同。

02
使用

下面是一些使用 round() 函数的示例:

  • 示例 1:四舍五入到整数

如果 ndigits 参数被省略,round() 函数会将浮点数四舍五入到最接近的整数。

print(round(3.14159))  # 输出: 3
print(round(2.71828))  # 输出: 3
print(round(-3.14159))  # 输出: -3

round() 函数遵循“银行家舍入”(Bankers’ rounding)规则,也称为偶数舍入。这意味着如果要舍弃的数字是5,而前面的数字是偶数,则舍入到最接近的偶数。如果前面的数字是奇数,则向上舍入到最接近的偶数。例如:

print(round(2.5))  # 输出: 2
print(round(3.5))  # 输出: 4
print(round(-2.5))  # 输出: -2
  • 示例 2:四舍五入到指定的小数位数

通过设置 ndigits 参数指定四舍五入的小数位数。

print(round(3.14159, 2))  # 输出: 3.14
print(round(2.71828, 3))  # 输出: 2.718
print(round(-3.14159, 2))  # 输出: -3.14


  • 示例 3:四舍五入到小数点左边的位数

如果 ndigits 为负数,round() 函数会将数字四舍五入到左边的小数点位置。

print(round(1234.567, -2))  # 输出: 1200.0
print(round(1234.567, -3))  # 输出: 1000.0
print(round(-1234.567, -2))  # 输出: -1200.0


  • 示例 4:浮点数的精度问题

需要注意的是,由于浮点数的精度问题,有时直接使用 round() 函数可能不会得到预期的结果,尤其是在处理非常小或非常大的浮点数时。

print(round(2.675, 2))  # 输出: 2.67而不是期望的 2.68

这种情况是由于浮点数在计算机内部的表示方式导致的,大多数十进制小数实际上都不能以浮点数精确地表示。 这种情况下可以考虑使用 decimal 模块,该模块提供了更精确的浮点数运算能力。

from decimal import Decimal, getcontext

# 设置全局精度,这里设置为3位小数
getcontext().prec = 3

# 使用Decimal对象来确保精度
number = Decimal('2.675')

getcontext().rounding = 'ROUND_HALF_UP'  # 设置舍入模式为四舍五入
result = number.quantize(Decimal('0.01'))
print(result)  
# 输出:2.68


本篇文章来源于微信公众号: 码农设计师

RELATED ARTICLES

欢迎留下您的宝贵建议

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments