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