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.