Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to round to higher 10's place in python

Tags:

python

math

I have a bunch of floats and I want to round them up to the next highest multiple of 10.

For example:

10.2 should be 20
10.0 should be 10
16.7 should be 20
94.9 should be 100

I only need it to go from the range 0-100. I tried math.ceil() but that only rounds up to the nearest integer.

Thanks in advance.

like image 269
Eric Avatar asked Oct 21 '10 11:10

Eric


1 Answers

from math import ceil

def ceil_to_tens(x):
    return int(ceil(x / 10.0)) * 10

Edit: okay, now that I have an undeserved "Nice answer" badge for this answer, I think owe the community with a proper solution using the decimal module that does not suffer from these problems :) Thanks to Jeff for pointing this out. So, a solution using decimal works as follows:

from decimal import Decimal, ROUND_UP

def ceil_to_tens_decimal(x):
    return (Decimal(x) / 10).quantize(1, rounding=ROUND_UP) * 10

Of course the above code requires x to be an integer, a string or a Decimal object - floats won't work as that would defeat the whole purpose of using the decimal module.

It's a pity that Decimal.quantize does not work properly with numbers larger than 1, it would have saved the division-multiplication trick.

like image 77
Tamás Avatar answered Sep 20 '22 16:09

Tamás