I want to round up integer to its next tens or hundreds. e.g. 12 -> 20 or 560 ->600. How can I do it?

+1 vote

Best answer

You can use the **round()** function to round an integer to its nearest tens, hundreds, thousands, etc.

E.g.

>>> round(150,-2)

200

>>> round(15,-1)

20

>>> round(12,-1)

10

But if you want to round to the next tens/hundreds, you can write a one-liner pythonic code.

E.g.

>>> n=12

>>> round(n,-1)+10 if round(n,-1)<n else round(n,-1)

20

>>> n=16

>>> round(n,-1)+10 if round(n,-1)<n else round(n,-1)

20

>>> n=156

>>> round(n,-2)+100 if round(n,-2)<n else round(n,-2)

200

>>> n=550

>>> round(n,-2)+100 if round(n,-2)<n else round(n,-2)

600