我想对代码中的数字进行四舍五入,但要以适应每个值的方式进行舍入。
例如,我想要返回舍入算法:
我事先不知道位数(这有点是我的问题)
我想用字符串来查找 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
import math
def round_(number):
dist = int(math.log10(abs(number))) #number of zeros after decimal point
return (round(number, abs(dist) + 2) if dist != 0 else round(number))
print(round_(0.999999))
print(round_(0.0749999))
print(round_(0.006599))
print(round_(-0.00043565))
输出:
1
0.075
0.0066
-0.00044
处理浮点数是很棘手的。您想要以 10 为基数进行舍入,但浮点数以 2 为基数。
所以我建议使用
decimal
模块,它可以准确地表示实数,而不是基数为 2 的浮点。:
from decimal import Decimal
def myround(num):
dec = Decimal(num)
adj = abs(dec.adjusted())+1
return round(num, adj)
查看 Decimal.adjusted()
的
文档以了解其工作原理。
测试:
In [1]: from decimal import Decimal
In [2]: def myround(num):
...: dec = Decimal(num)
...: adj = abs(dec.adjusted())+1
...: return round(num, adj)
...:
In [3]: myround(0.999999)
Out[3]: 1.0
In [4]: myround(0.006599)
Out[4]: 0.0066
In [5]: myround(0.0749999)
Out[5]: 0.075
使用@ncica的代码,这可能稍微更通用和干净:
def smart_round(number: float, round_to: int) -> float:
if number == 0:
return number
zeros_after_point = abs(int(math.log10(abs(number))))
return round(number, zeros_after_point + round_to)