python - Fastest Way to Round to the Nearest 5/100ths -


i have numbers want go from:

1.215145156155 => 1.2 1.368161685161 => 1.35 1.578414616868 => 1.6 

(*note: hundredths place should not marked if zero.)

what's fastest way this?

this have right now, , 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 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 behaviour might surprise you:

>>> round(20*1.368161685161)/20 1.3500000000000001 

the rounding working correctly, ieee numbers can't represent 1.35 exactly. python 2.7 smarter , choose simplest representation, 1.35, when printing number. actual stored value identical in 2.7 , earlier versions.


Comments