Search code examples
pythonroundingfloorceil

how to find nearest equal or higher multiple of ten in python


I have a this small task , where I am rounding up the number to higher multiple of ten. But want to round it to nearest multiple of ten.

My code :

import math

a = map(int,list(str(7990442)))
b = map(int,list(str(1313131)))
print "a :",a
print "b :",b

l= []
for p,q in zip(a,b):
    l.append(p*q)
print "prod list :",l
ls = sum(l)
print "sum :",ls
def roundup(x):
    return int(math.ceil(x / 10.0)) * 10
top = roundup(ls)
print "round value: ",top
val = top-ls
print "val :",val
a.append(val)
print "output :",a

Output :

a : [7, 9, 9, 0, 4, 4, 2]
b : [1, 3, 1, 3, 1, 3, 1]
prod list : [7, 27, 9, 0, 4, 12, 2]
sum : 61
round value:  70
val : 9
output : [7, 9, 9, 0, 4, 4, 2, 9]

Expected Output :

sum : 61
round value:  60
val : 1
output : [7, 9, 9, 0, 4, 4, 2, 1]

Solution

  • You can use round(x / 10.0) * 10 instead of math.ceil.

    Even easier would be

    def custom_round(x):
        return int(round(x, -1))
    

    This immediately rounds to a multiple of ten.