流暢的python和cookbook學習筆記(四),pythoncookbook

來源:互聯網
上載者:User

流暢的python和cookbook學習筆記(四),pythoncookbook
1.數位四捨五入

  對於簡單的舍入運算,使用內建的 round(value, ndigits) 函數即可。

  round 函數返回離它最近的偶數。也就是說,對 1.5 或者 2.5 的舍入運算都會得到 2。

>>> round(2.5)2>>> round(1.5)2

  round()的參數ndigits可以是負數,取整到十位,百位,千位, 效果如下:

>>> a = 13123213>>> round(a, -1)13123210>>> round(a, -2)13123200>>> round(a, -3)13123000

  不要將舍入和格式化輸出搞混淆了。如果你的目的只是簡單的輸出一定寬度的數, 不需要使用 round() 函數。只需要在格式化的時候指定精度即可。

>>> x = 1.231231241>>> format(x, '0.4f')'1.2312'>>> 'value is {:0.3f}'.format(x)'value is 1.231'
2.精確的小數計算

  浮點數無法精確的表達出所有的十進位小數位。

>>> a = 4.2>>> b = 2.1>>> a + b6.300000000000001>>> (a + b) == 6.3False

  可以使用decimal模組來提高精確值,但是要犧牲一些效能。

>>> from decimal import Decimal>>> a = Decimal('4.2')>>> b = Decimal('2.1')>>> a + bDecimal('6.3')>>> print(a + b)6.3>>> (a + b) == Decimal('6.3')True

  控制位元和四捨五入。

>>> from decimal import localcontext>>> a = Decimal('1.4')>>> b = Decimal('1.9')>>> print(a/b)0.7368421052631578947368421053>>> with localcontext() as num:...     num.prec = 3...     print(a/b)...0.737>>> with localcontext() as num:...     num.prec = 50...     print(a/b)...0.73684210526315789473684210526315789473684210526316
3.格式化數值

  使用內建函數format(),可以自訂保留多少位,置中等操作。想採用科學計演算法,把 f 改為 e 或 E 即可。

>>> x = 1234.56789>>> format(x, '0.2f') # 保留兩位小數'1234.57'>>> format(x, '>10.1f')  #左邊留白'    1234.6'>>> format(x, '<10.1f')  #右邊留白'1234.6    '>>> format(x, '^10.1f')  # 置中'  1234.6  '>>> format(x, ',')          # 顯示千位'1,234.56789'>>> format(x, '0.1f')     # 保留一位小數'1234.6'

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.