Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to the nearest 500, Python

I'm looking to find a way to round up to the nearest 500.I've been using:

math.ceil(round(8334.00256 + 250, -3))

Whereby I have a value from a scale in a map I am making in ArcGIS. I have the ability to read and write the scale factor (i.e. 1:8334....basically, you set the thousandth and it defaults to a ratio) If the scale factor isn't a factor of 500, I want to round up to the next 500. The math.ceil will round up any decimal value, and the round(n,-3) will round to the nearest thousandth, but I'm struggling to find a way to round to the nearest 500.

Any suggestions? Thanks, Mike

like image 378
Mike Avatar asked Mar 21 '12 18:03

Mike


People also ask

How do you round to the nearest 500 in Python?

Round a number Up to the nearest 500 in Python #Call the math. ceil() method passing it the number divided by 500 . Multiply the result by 500 .

How do you round a number to the nearest 500?

(1) Divide the number by 500. This tells you how many 500's you have. (2) Round that to the nearest integer because that represents the numbers in between. (3) Multiply by 500.

How do you round to hundreds in Python?

Use the round() function to round a number to the nearest 100, e.g. result = round(num, -2) . When the round() function is called with a second argument of -2 , it rounds to the closest multiple of one hundred.

How do you round to the nearest number in Python?

Python does have two methods that let you round up and down. The floor() method rounds down to the nearest integer. ceil() rounds up to the nearest integer.


2 Answers

Scale, round, unscale:

round(x / 500.0) * 500.0

Edit: To round up to the next multiple of 500, use the same logic with math.ceil() instead of round():

math.ceil(x / 500.0) * 500.0
like image 63
Sven Marnach Avatar answered Oct 14 '22 05:10

Sven Marnach


I personally find rounding a but messy. I'd rather use:

(x+250)//500*500

// means integer division.

EDIT: Oh, I missed that you round "up". Then maybe

-(-x//500)*500
like image 21
Gerenuk Avatar answered Oct 14 '22 04:10

Gerenuk