Python中的数字运算及相关转换

1. 取整:


(1) int(): 类型工厂函数。
对于浮点数只截取整数部分,丢弃小数部分
int(3.1)   返回:3
int(3.5)  返回:3
int(3.923)  返回:3
int(-12.34)  返回:-12
数字字符串转换为整数:
  int('23')     返回:23     # 默认base=10 (Valid bases are 0 and 2-36) 
int('23', base=8)  返回:19   (8进制)
int('23', base=16)   返回:35
int('A', base=16),  int('0a', base=16), int('0x0a', base=16)   都返回:10
int('0b100', base=2)   返回:4


无法转换的情况:
int('-123.45')    错误:无法转换
int('34.45')   错误:无法转换
int('23a')    错误:无法转换


不同进制数的表示方法:
八进制:0o177, 0O177  (十进制127)   Python3.x表示方法,Python2.x中表示为: 0177
十六进制:0x9ff,0X9FF
二进制:0b101010,  0B101010  


将整数转换为不同进制的字符串:
hex(I):将给定的整数转换为十六进制表示的字符串
hex(100)    返回:'0x64'
hex(0xAF)    返回:'0xaf'
oct(I):将给定的整数转换为八进制表示的字符串
oct(100)     返回:'0o144'
oct(0O100)    返回: '0o100'
bin(I):将给定的整数转换为二进制表示的字符串
bin(10)     返回:'0b1010'
bin(0B10)   返回:'0b10'


使用str()函数将数字转换为字符串:
str(100)   返回:'100'
str(-100)   返回:'-100'
str(12.23)   返回:'12.23'
str(-34.23)  返回:'-34.23'
str(0x123)   返回:'291'
str(2.0)    返回:'2.0'
str(2.00)    返回:'2.0'
str(float(2))   返回:'2.0'
str(float(-2))   返回:'-2.0'
str(float('3.24'))  返回:'3.24'
str(12a)   错误:语法错误

(2) 内置函数round():四舍五入取整
round(number, ndigits=None)  # ndigits是保留小数点后几位,默认为0
round(2.3)   返回:2
round(2.8)   返回:3
round(0.5)   返回:0     ???
round(1.5)   返回:2
round(2.5)   返回:2     ???
round(3.5)   返回:4
round(4.5)   返回:4     ???
round(4.501)   返回:5
round(5.5)   返回:6
   ### 整数位为奇数时,小数为.5时取整时可以进位,但如果整数位为偶数时,小数为.5时取整时是不进位的???
round(-2.4)   返回:-2 
round(-2.5)   返回:-2    ???
round(-2.6)   返回:-3
round(-3.4)   返回:-3 
round(-3.5)   返回:-4   
round(-3.6)   返回:-4
(3) math模块的floor()函数:取小于等于的整数
math.floor(0.3)  返回:0
math.floor(-0.3)  返回:-1   # 与int(-0.3)=0不同
math.floor(1.5)  返回:1
math.floor(1.8)  返回:1
math.floor(-1.1)  返回:-2
math.floor(-1.8)  返回:-2



2. 浮点数保留几位小数:


(1) 内置函数round():
round(number, ndigits=None)  # ndigits是保留小数点后几位,默认为0
round(2,1)   返回:2
round(2.0,1)   返回:2.0
round(2.2,1)   返回:2.2


round(2.24,1)   返回:2.2
round(2.25,1)   返回:2.2  ???
round(2.26,1)   返回:2.3


round(2.34,1)   返回:2.3
round(2.35,1)   返回:2.4
round(2.36,1)   返回:2.4


round(3.24,1)   返回:3.2
round(3.25,1)   返回:3.2
round(3.26,1)   返回:3.3


round(3.34,1)   返回:3.3
round(3.35,1)   返回:3.4
round(3.36,1)   返回:3.4

round(1.23456, 4)  返回: 1.2346


(2) float(): 类型工厂函数。
float(2)  返回:2.0
float(-2)  返回:-2.0
float(2.134)  返回:2.134
float('2') 返回:2.0  
float('-2')  返回:-2.0
float('-2.3456')  返回:-2.3456
float('-2.34a')   错误:无法转换


(3) 浮点数转换为字符串:
str(2.0)    返回:'2.0'
str(2.00)    返回:'2.0'
str(-3.24)    返回:'-3.24'
'%f'%2   返回:'2.000000'
'%f'%2.0   返回:'2.000000'
'%f'%2.01   返回:'2.010000'
'%.2f'%2   返回:'2.00'
'%.4f'%2.123456   返回:'2.1235'  # 四舍五入 

猜你喜欢

转载自blog.csdn.net/youngwhz1/article/details/51660865