Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest Way to Round to the Nearest 5/100ths

Tags:

python

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 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)
like image 438
thenickname Avatar asked Dec 02 '10 21:12

thenickname


People also ask

How do you round a number to the nearest 5?

Use your number line, number from 1-10 and jump from 9 back to 5 and from 9 forward to 10. They can see that you have to jump 4 times to get to 5 but only once to get to 10. 9 rounded of to the nearest 5 is then equal to 10.

What does round to 5 decimal places mean?

"To five places" means "to five decimal places". First, I count out the five decimal places, and then I look at the sixth place: 3.14159 | 265... I've drawn a little line separating the fifth place from the sixth place. This can be a handy way of "keeping your place", especially if you are dealing with lots of digits.


2 Answers

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.

like image 155
Marcelo Cantos Avatar answered Sep 23 '22 10:09

Marcelo Cantos


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
like image 38
Sven Marnach Avatar answered Sep 21 '22 10:09

Sven Marnach