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
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 .
(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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With