python實現四舍五入


由於python的round進行四舍五入時是遇六進一而不是遇五進一,所以要從新編寫一個算法
具體代碼如下
#coding:utf-8

class round(object):

#返回浮點數類型的值
def roundF(self, value, digit):
result = str(value)
if (float(value) < 0):
result = result[1:]
if (result != ''):
indexDec = result.find('.')
if (indexDec > 0):
decimal = result[indexDec + 1:]
decimalCount = len(decimal)
if (decimalCount > digit):
xiaoshu = result[indexDec + digit + 1] # 第digit+1位小數
if (int(xiaoshu) > 4):
result = str(float(value) * -1 + pow(10, digit * -1))
# 存在進位的可能,小數點會移位
indexDec = result.find('.')
result = result[:indexDec + digit + 1]
else:
result = result[:indexDec + digit + 1]
else:
lens = digit - len(result[indexDec:]) + 1
for i in range(lens):
result += '0'
result = float(result) * -1
return result
else:
if (result != ''):
indexDec = result.find('.')
if (indexDec > 0):
decimal = result[indexDec + 1:]
decimalCount = len(decimal)
if (decimalCount > digit):
xiaoshu = result[indexDec + digit + 1] # 第digit+1位小數
if (int(xiaoshu) > 4):
result = str(float(value) + pow(10, digit * -1))
# 存在進位的可能,小數點會移位
indexDec = result.find('.')
result = result[:indexDec + digit + 1]
else:
result = result[:indexDec + digit + 1]
else:
lens = digit - len(result[indexDec:]) + 1
for i in range(lens):
result += '0'
return float(result)

#返回字符串類型的值
def roundStr(self,value, digit):
result = str(value)
if (float(value) < 0):
result = result[1:]
if (result != ''):
indexDec = result.find('.')
if (indexDec > 0):
decimal = result[indexDec + 1:]
decimalCount = len(decimal)
if (decimalCount > digit):
xiaoshu = result[indexDec + digit + 1] # 第digit+1位小數
if (int(xiaoshu) > 4):
result = str(float(value) * -1 + pow(10, digit * -1))
# 存在進位的可能,小數點會移位
indexDec = result.find('.')
result = result[:indexDec + digit + 1]
else:
result = result[:indexDec + digit + 1]
else:
lens = digit - len(result[indexDec:]) + 1
for i in range(lens):
result += '0'
# result = float(result) * -1
return '-'+result
else:
if (result != ''):
indexDec = result.find('.')
if (indexDec > 0):
decimal = result[indexDec + 1:]
decimalCount = len(decimal)
if (decimalCount > digit):
xiaoshu = result[indexDec + digit + 1] # 第digit+1位小數
if (int(xiaoshu) > 4):
dg=pow(10, digit * -1)
result = str(float(value) +dg )
# 存在進位的可能,小數點會移位
indexDec = result.find('.')
result = result[:indexDec + digit + 1]
else:
result = result[:indexDec + digit + 1]
else:
lens = digit - len(result[indexDec:]) + 1
for i in range(lens):
result += '0'
return result

if __name__ == '__main__':
d=round().roundStr(2346.23502,4)
print(d)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM