1

Lets say I have a list of numbers: [0.13,0.53,2.83] I want these numbers to round UP to the nearest x=0.5 (or any other value for x) This list would then become, given x=0.5: [0.5,1,3].

I tried somethings with % but neither of what I tried seemed to work.

Any ideas?

Harry

EDIT: the other posts want to know the nearest value, so 1.6 would become 1.5, but in my case it should become 2

3 Answers3

4

You need math.ceil:

import math

numbers = [0.13, 0.53, 2.83]
x = 0.5

def roundup(numbers, x):
    return [math.ceil(number / x) * x for number in numbers]

roundup(numbers, x)
# returns [0.5, 1.0, 3.0]
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • This answer should not have been accepted. For example when x=0.6 then your function returns "number + {0, 0.6 or 1.2}" while I think the expected result is "number + {0, 0.6 or 1}". – T.Lucas Sep 09 '19 at 10:09
0

If a function suits your need then the function bellow works for positive numbers. "x" is the number you want to round and thresh is the value (between 0 and 1) used to round up.

def rounding_function(x, thresh):
    if x == int(x):
        return x
    else:
        float_part = x-int(x)
        if float_part<=thresh:
            return int(x) + thresh
        else:
            return int(x) + 1

Which gives the following result:

l = [0, 0.13,0.53, 0.61, 2.83, 3]

print([rounding_function(x, 0.5) for x in l]) # [0, 0.5, 1, 1, 3, 3]
print([rounding_function(x, 0.6) for x in l]) # [0, 0.6, 0.6, 1, 3, 3]
T.Lucas
  • 848
  • 4
  • 8
0

Here's a general solution. (Don't forget to handle all the "weird input"; e.g. negative incr, negative x, etc.)

import math

def increment_ceil(x, incr=1):
    """ 
    return the smallest float greater than or equal to x
    that is divisible by incr
    """
    if incr == 0:
        return float(x)
    else:
        return float(math.ceil(x / incr) * incr)
Dan Pittsley
  • 143
  • 7