Round to the nearest 500, Python
Solution 1
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
Solution 2
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
Solution 3
Maybe something like this:
round(float(x) / 500) * 500
The "float" conversion is unnecessary if you are using Python 3 or later, or if you run the statement from __future__ import division
for sane integer division.
Mike
Updated on July 09, 2022Comments
-
Mike almost 2 years
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
-
Mike about 12 yearsThe issue is, that I need to round UP to the nearest 500, not just round either way. If I plug x = 8001, your logic rounds to 8000. I need 8500....
-
Mike about 12 yearsSee comment below Sven's suggestion. Thanks.
-
Mike about 12 yearsSven, I started working with round(x/500.0 + 0.5)*500 which gives me the result I was looking for. I'm using the math module anyways, so I'm going to use your syntax. Thanks for the help.
-
Elias Zamaria about 12 yearsSven's idea seems better. I just typed the first reasonable thing I thought of.
-
Alex L almost 11 yearsSteven's method is faster:
timeit.timeit('math.ceil(x / 500.0) * 500.0', 'import math; x=5200') = 0.539998
vs>>> timeit.timeit('x + (500 - x) % 500', 'x=5200') = 0.23273
-
Sven Marnach almost 11 years@AlexL: Usually, readability matters more than speed, and I think my approach is more readable. That said, it is also faster (at least on my machine) if you eliminate the attribute look-up for
ceil
, i.e. if you usefrom math import ceil
. -
PolyGeo about 7 years@StevenRumbalski I think you should write that as an answer (with just a little description added)
-
Agent Lu almost 5 years@SvenMarnach Hey I was looking through this and needed to round down 500 and I think it would be helpful to add the
math.floor()
variant. I added an edit for you. Thanks :)