1.數字的舍入python
>>> round(1.23,1) 1.2
當一個值恰好在兩個邊界的中間的時候,round
函數返回離它最近的偶數。僅在python3中如此git
python3 >>> round(1.5) 2 >>> round(2.5) 2 -------------------------------------------- python2 >>> round(1.5) 2.0 >>> round(2.5) 3.0
2.執行精確地十進制運算web
>>> a = 4.2 >>> b = 2.1 >>> a + b 6.300000000000001 >>> (a + b) == 6.3 False
>>> from decimal import Decimal >>> a = Decimal('4.2') >>> b = Decimal('2.1') >>> a+bDecimal('6.3') >>> a+b== Decimal('6.3') True
decimal模塊的一個主要特徵是容許你控制計算的每一方面,包括數字位數和四捨五入運算函數
decimal.localcontext([c])性能
返回上下文管理器會將活動線程的當前上下文設置爲c的複印件在 with 語句進入和退出 with 語句時恢復之前的上下文。若是指定了沒有上下文,則使用當前上下文的副本。spa
>>> from decimal import localcontext >>> a= Decimal('1.3') >>> b= Decimal('1.7') >>> a/bDecimal('0.7647058823529411764705882353') >>> print a/b0.7647058823529411764705882353 >>> with localcontext() as ctx: ... ctx.prec = 3 ... print a/b ... 0.765 math.fsum(iterable)在可迭代中返回值的準確浮動點總和。經過跟蹤多箇中間部分款項,避免了精度損失 >>> nums = [1.23e+18, 1, -1.23e+18] >>> sum(nums) #注意1消失了 0.0 上述錯誤能夠利用 math.fsum() 所提供的更精確計算能力來解決 >>> import math >>> math.fsum(nums) 1.0
3. 數字的格式化輸出
線程
格式化輸出單個數字的時候,可使用內置的 format()
函數code
>>> x = 1234.56789 #保留兩位小數 >>> format(x, '0.2f') '1234.57' #佔10個字符,靠右,保留一位小數 >>> format(x, '>10.1f') ' 1234.6' #逗號分隔 >>> format(x, ',') '1,234.56789' >>> format(x, '0,.1f') '1,234.6' #指數記法,將f改爲e或者E(取決於指數輸出的大小寫形式) >>> format(x, 'e') '1.234568e+03' >>> format(x, '0.2E') '1.23E+03'
同時指定寬度和精度的通常形式是 '[<>^]?width[,]?(.digits)?'
, 其中 width
和 digits
爲整數,?表明可選部分。 一樣的格式也被用在字符串的 format()
方法中。orm
>>> x = 1234.56789 >>> 'The value is {:0,.2f}'.format(x) 'The value is 1,234.57'
當用format指定數字的位數後,結果值會根據 round()
函數一樣的規則進行四捨五入後返回。ci
>>> x=1234.56789 >>> format(x, '0.1f') '1234.6' >>> format(-x, '0.1f') '-1234.6'
4.二八十六進制整數
>>> x = 1234 >>> bin(x) '0b10011010010' >>> oct(x) '0o2322' >>> hex(x) '0x4d2' 若是你不想輸出 0b , 0o 或者 0x 的前綴的話,可使用 format() 函數 >>> format(x, 'b') '10011010010' >>> format(x, 'o') '2322' >>> format(x, 'x') '4d2' 爲了以不一樣的進制轉換整數字符串,簡單的使用帶有進制的int()函數便可: >>> int('4d2', 16) 1234 >>> int('10011010010', 2) 1234