四舍五入:round(number,precision) 有精度,默认精度为0 即取整
>>> round(1.23,1)
1.2
>>> round(-1.23,1)
-1.2
>>> round(123,-2)
100
进一法(math.ceil())去尾法(math.floor()):取整
>>> import math
>>> math.floor(12.3)12
>>> math.ceil(12.3)
13
>>> math.ceil(-12.3)
-12
>>> math.floor(-12.3)
-13
格式化:采用的四舍五入 '[<>^]?width[,]?(.digits)?'
>>> x = 1234.56789
>>> format(x,"0.2f")
'1234.57'
>>> format(x,">0.2f")
'1234.57'
>>> format(x,">10.2f")
' 1234.57'
>>> format(x,"<10.2f")
'1234.57 '
>>> format(x,"^10.2f")
' 1234.57 '
>>> format(x,",")
'1,234.56789'
>>> format(x,"0,.2f")
'1,234.57'
>>> format(x,"10.2e")
' 1.23e+03'
>>> format(x,"10,.2f")
' 1,234.57'
>>> format(x,",.2f")
'1,234.57'
>>> "{:0.2f}".format(x)
'1234.57'
精确计算,浮点数的计算会有些许误差,引入 decimal
<class 'decimal.Decimal'>采用字符构造对象
>>> from decimal import Decimal
>>> a= Decimal('4.2')
>>> b= Decimal("2.1")
>>> a+b
Decimal('6.3')
>>> a+b ==Decimal("6.3")
True
>>> a+b ==6.3#左边是Decimal对象 右边是浮点数
False
>>> print(a+b)
6.3
>>>
>>> from decimal import localcontext
>>> a= Decimal('1.3')
>>> b= Decimal("1.7")
>>> print(a/b)
0.7647058823529411764705882353
>>> with localcontext() as ctx:
ctx.prec = 3
print(a/b)
0.765
浮点数计算是数量级差得很多的时候需要格外小心误差
>>> nums = [1.23e+18,1,-1.23e+18]
>>> sum(nums)
0.0
>>> import math
>>> math.fsum(nums)
1.0
进制转换:bin(),oct(),hex() int(xxx,base); 'b','o','x'
>>> x = 1234
>>> bin(x)
'0b10011010010'
>>> oct(x)
'0o2322'
>>> hex(x)
'0x4d2'
>>> format(x,'b')
'10011010010'
>>> format(x,'o')
'2322'
>>> format(x,'x')
'4d2'
>>> y = -1234
>>> format(x,'b')
'10011010010'
>>> y = -1234
>>> format(y,'b')
'-10011010010'
>>> format(2**32+y,'b')
'11111111111111111111101100101110'
>>> format(y,'o')
'-2322'
>>> format(2**32+y,'o')
'37777775456'
>>> format(y,'x')
'-4d2'
>>> format(2**32+y,'x')
'fffffb2e'
>>> int('4d2',16)
1234