round函数python负数_如果说Python的round函数不准确,可以自己编写,大家,那,就,写个准,呗...

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不准,那就自己写个准的呗,其实不难哈哈,我这个虽然有点取巧,但结果绝对是四舍五入,嘎嘎。

当然这个我刚写出来,用的不多,如果有问题大家联系我

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值