如何在 Python 中对数字进行四舍五入

2021-09-07 10:59:25 浏览数 (6308)

大家好,在本篇文章中,我们将了解 round() 在 Python 编程中处理十进制数时对数字进行四舍五入的方法。

一、简介

round()​:python中用于在处理十进制数时对数字进行四舍五入的方法。它用以下语法表示:

round(number, digits)
  • number 是要四舍五入的数字的必需参数
  • digits 是四舍五入时要使用的小数位数的可选参数

        ◦ 是默认为 0

        ◦ 如果小数点后的最后一位数字 >=5,它将四舍五入到下一个整数

        ◦ 如果小数点后的最后一位数字 <5 将四舍五入到地板整数

二、如何在 Python 中四舍五入

2.1 缺少十进制参数时

让我们在代码片段的帮助下理解这一点。

当十进制参数丢失时

def method1():
    print(round(10))
    print(round(10.2))
    print(round(10.6))
def main():
    print('==== if the decimal param is not present =====')
    method1()
if __name__ == '__main__':
    main()

控制台输出如果一切顺利,IDE 控制台中将显示以下输出。

==== if the decimal param is not present =====
10
10
11

让我们在代码片段的帮助下理解这一点。2.2 当十进制参数存在时

当十进制参数存在时


def method2():
    print(round(10.465, 2))
    # if the last digit after the decimal is >=5, it will be round off to the next integer
    print(round(10.466, 2))
    # if the last digit after the decimal is <5, it will be round off to the floor integer
    print(round(10.463, 2))
def main():
    print('\n==== if the decimal param is present =====')
    method2()
if __name__ == '__main__':
    main()

如果一切顺利,IDE 控制台中将显示以下输出。

控制台输出

==== if the decimal param is present =====
10.46
10.47
10.46

这就是本篇文章的全部内容,我希望这篇文章能够为你提供所需的一切。快乐学习,不要忘记分享!

三、总结

在本教程中,我们学到了——

  • round() python编程中的方法介绍
  • 理解round()方法的示例程序