赞
踩
def newRound(x,n=0):
if isinstance(x,float) ==False: #x不是浮点
result ='x = '+ str(x) +' 必须为小数 '
return result
if n < 0: #n为负数
result ='n = '+ str(n) +' 不能小于0 '
return result
y = str(x) #浮点转字符串
aDotNumList = y.split(".") #字符串按小数点分开成列表
orderNum = aDotNumList[1] #列表只有[0]和[1],[0]是小数点前的数,[1]是小数点后的数
if len(orderNum)>n:
intY = int(orderNum[n]) #取第n位的数,因为python从0开始所以从n判断就可以了
else:
result ='n = '+str(n)+' 必须小于小数点后数字长度 '+ str(len(orderNum))
return result
if intY < 5 and n > 0: #四舍,n大于0
aDotNumList[1]=int(orderNum[:n])
elif intY >= 5 and n > 0: #五入,n大于0
aDotNumList[1]=int(orderNum[:n]) + 1
elif intY < 5 and n == 0 : #四舍,n等于0
aDotNumList[0] = aDotNumList[0]
aDotNumList[1] = 0
elif intY >= 5 and n == 0 : #五入,n等于0
if x >0: #如果x为正数
aDotNumList[0] = int(aDotNumList[0]) + 1
else: #如果x不为正数
aDotNumList[0] = int(aDotNumList[0]) - 1
aDotNumList[1] = 0
x = str(aDotNumList[0]) + "." + str(aDotNumList[1]) #整数部分加上小数部分
result = float(x) #String转化成float
return result
大家说round不准,那就自己写个准的呗,其实不难哈哈,我这个虽然有点取巧,但结果绝对是四舍五入,嘎嘎。
当然这个我刚写出来,用的不多,如果有问题大家联系我
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。