我想对代码中的数字进行四舍五入,但要以适应每个值的方式进行舍入。
例如,我想要返回舍入算法:
- 0.999999 它应该返回 1
- 0.0749999 它应该返回 0.075
- 0.006599 它应该返回 0.0066 等等...
我事先不知道位数(这有点是我的问题)
我想用字符串来查找 9 在哪里(或数 0),但我想这需要付出很大的努力?
如果您知道有什么方法可以做到这一点(如果可能的话,无需高级库),我将不胜感激。
谢谢。
最佳答案
有点复杂。但是,它有效。请确保结果是您想要的。我想你可以理解如何从代码中对数字进行四舍五入。
def clear9(numstr):
liststr = list(numstr)
for index in range(len(liststr)-1,-1,-1):
if liststr[index] == '.': continue
if liststr[index] == '9':
liststr[index] = '0'
if index == 0:
liststr.insert(0, '1')
else:
if index != len(liststr)-1:
liststr[index] = str(int(liststr[index])+1)
break
numstr = ''
for item in liststr:
numstr += item
return numstr
def myround(num):
numstr = str(num)
numstr = clear9(numstr)
return float(numstr)
print (myround(9.05))
print (myround(9.999999))
print (myround(0.999999))
print (myround(0.0749999))
print (myround(0.006599))
print (myround(0.00659923))
print (myround(0.09659923))
print (myround(-0.00659923))
9.05
10.0
1.0
0.075
0.0066
0.00659923
0.09659923
-0.00659923
关于python-3.x - 如何让算法自动以 "smart"方式循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56264675/