from math import ceil def ceil_to_tens(x): return int(ceil(x / 10.0)) * 10
Edit : ok, now that I have the undeserved "Good Answer" badge for this answer, I believe that the community should have the right solution using the decimal module, which does not suffer from these problems :) Thanks to Jeff for this. Thus, 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 that x be an integer, string, or decimal object - floats will not work, as this can damage the whole purpose of using the decimal module.
It is Decimal.quantize that Decimal.quantize does not work properly with digits greater than 1, this would save the division-multiplication trick.
TamΓ‘s
source share