Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - round up to the nearest ten [duplicate]

If I get the number 46 and I want to round up to the nearest ten. How do can I do this in python?

46 goes to 50.

like image 902
raspberrysupreme Avatar asked Oct 19 '14 19:10

raspberrysupreme


People also ask

How do you round doubles in Python?

Round() Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.

How do I find the nearest multiple of a number in Python?

You can use round(x / 10.0) * 10 instead of math. ceil . This immediately rounds to a multiple of ten.

How do you round up by 10 in python?

To round number to nearest 10, use round() function. We can divide the value by 10, round the result to zero precision, and multiply with 10 again. Or you can pass a negative value for precision. The negative denotes that rounding happens to the left of the decimal point.

How do I always round up in Python?

To implement the “rounding up” strategy in Python, we'll use the ceil() function from the math module. The ceil() function gets its name from the term “ceiling,” which is used in mathematics to describe the nearest integer that is greater than or equal to a given number.


2 Answers

round does take negative ndigits parameter!

>>> round(46,-1) 50 

may solve your case.

like image 157
ch3ka Avatar answered Oct 06 '22 06:10

ch3ka


You can use math.ceil() to round up, and then multiply by 10

import math  def roundup(x):     return int(math.ceil(x / 10.0)) * 10 

To use just do

>>roundup(45) 50 
like image 36
Parker Avatar answered Oct 06 '22 06:10

Parker