Fastest Way to Round to the Nearest 5/100ths
I have numbers that I want to go from:
1.215145156155 => 1.2
1.368161685161 => 1.35
1.578414616868 => 1.6
(*Note: the hundredths place should not be marked if it is zero.)
What's the fastest way to do this?
This is what I have right now, and it is not fast enough:
def rounder(v):
v = str(round(float(v),2))
if len(v) == 3: v = v + str(0)
d0 = int(v[0])#ones
d1 = int(v[2])#tenths
d2 = int(v[3])#hundredths
if d2 <= 4:
return str(d0)+'.'+str(d1)
elif开发者_如何学Go 4 < d2 < 7:
return str(d0)+'.'+str(d1)+str(5)
elif d2 >= 7:
if d1 != 9:
return str(d0)+'.'+str(d1+1)
if d1 == 9:
return str(d0+1)+'.'+str(0)
Scale, round, unscale.
round(20*v)/20
I should warn you that the behaviour might surprise you:
>>> round(20*1.368161685161)/20
1.3500000000000001
The rounding is working correctly, but IEEE numbers can't represent 1.35 exactly. Python 2.7 is smarter about this and will choose the simplest representation, 1.35
, when printing the number. The actual stored value is identical in 2.7 and earlier versions.
I would try
round(v * 2, 1) / 2
Should be pretty fast. The other suggested variant
round(v * 20) / 20
seems to be even slightly faster:
$ python -mtimeit "round(1.368161685161 * 2, 1) / 2"
1000000 loops, best of 3: 0.291 usec per loop
$ python -mtimeit "round(1.368161685161 * 20) / 20"
1000000 loops, best of 3: 0.248 usec per loop
精彩评论