App下載

如何在 Python 中對數(shù)字進(jìn)行四舍五入

月亮郵遞員 2021-09-07 10:59:25 瀏覽數(shù) (7046)
反饋

大家好,在本篇文章中,我們將了解 round() 在 Python 編程中處理十進(jìn)制數(shù)時對數(shù)字進(jìn)行四舍五入的方法。

一、簡介

?round()?:python中用于在處理十進(jìn)制數(shù)時對數(shù)字進(jìn)行四舍五入的方法。它用以下語法表示:

round(number, digits)
  • number 是要四舍五入的數(shù)字的必需參數(shù)
  • digits 是四舍五入時要使用的小數(shù)位數(shù)的可選參數(shù)

        ? 是默認(rèn)為 0

        ? 如果小數(shù)點(diǎn)后的最后一位數(shù)字 >=5,它將四舍五入到下一個整數(shù)

        ? 如果小數(shù)點(diǎn)后的最后一位數(shù)字 <5 將四舍五入到地板整數(shù)

二、如何在 Python 中四舍五入

2.1 缺少十進(jìn)制參數(shù)時

讓我們在代碼片段的幫助下理解這一點(diǎn)。

當(dāng)十進(jìn)制參數(shù)丟失時

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

讓我們在代碼片段的幫助下理解這一點(diǎn)。2.2 當(dāng)十進(jìn)制參數(shù)存在時

當(dāng)十進(jìn)制參數(shù)存在時


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

這就是本篇文章的全部內(nèi)容,我希望這篇文章能夠?yàn)槟闾峁┧璧囊磺???鞓穼W(xué)習(xí),不要忘記分享!

三、總結(jié)

在本教程中,我們學(xué)到了——

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


0 人點(diǎn)贊