python中round(x,[n])的使用

來源:互聯網
上載者:User
round(x,[n]) 四捨五入 n保留小數部分個數

1、當不填寫n時,預設為0,即不保留小數部分
  a、當小數部分只為0.5時 整數部分如果為奇數則進1,如果為偶數則捨去小數部分
  print(round(1.5))#2 小數部分為0.5 整數部分為奇數則+1
  print(round(2.5))#2 小數部分為0.5 整數部分為偶數則捨去小數部分
  print(round(-1.5))#-2
  print(round(-2.5))#-2
  print(round(1.4))#1
  print(round(2.4))#2
  print(round(-1.4))#-1
  print(round(-2.4))#-2
  b、小數部分不為0.5時 按四捨五入
  print(round(1.54))#2 小數0.54 進1
  print(round(2.54))#3
  print(round(-1.54))#-2
  print(round(-2.54))#-3
  print(round(1.45))#1 小數0.45 捨去
  print(round(2.45))#2
  print(round(-1.45))#-1
  print(round(-2.45))#-2

2、當保留小數部分時
  a、當小數部分保留數位置後一位為5時,保留數位置數為偶數時進1,奇數捨去
  print(round(2.635, 2))#2.63 保留數後一位為5,保留位置是3為奇數,則不進1
  print(round(2.645, 2))#2.65 保留數後一位為5,保留位置是4為偶數,則進1
  print(round(2.655, 2))#2.65
  print(round(2.665, 2))#2.67
  print(round(2.675, 2))#2.67
  b、當保留數位置後一位不為5時,按四捨五入
  print(round(2.636, 2))#2.64
  print(round(2.646, 2))#2.65
  print(round(2.656, 2))#2.66
  print(round(2.666, 2))#2.67
  print(round(2.676, 2))#2.68

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.