这篇“怎么在Python中对数字进行四舍五入”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“怎么在Python中对数字进行四舍五入”文章吧。
一、简介
round()
:python中用于在处理十进制数时对数字进行四舍五入的方法。它用以下语法表示:
round(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
以上就是关于“怎么在Python中对数字进行四舍五入”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注天达云行业资讯频道。