Round to a nearest multiple of a constant?

Obviously, we can round/floor/ceiling to the nearest integer but how can I round to, say, the nearest multiple of 45? This seems like it should be very easy, so I feel like I’m missing something simple.

Thanks

I have no idea if there is a node for that, but this here should do what you want:

I just converted this code to BP:



int roundUp(int numToRound, int multiple) 
{ 
    if (multiple == 0) 
        return numToRound; 

    int remainder = abs(numToRound) % multiple;
    if (remainder == 0)
        return numToRound;
    if (numToRound < 0)
        return -(abs(numToRound) - remainder);
    return numToRound + multiple - remainder;
}


2 Likes

Yep, it sure does. Thanks, eXi.

Forgive me if I’m wrong, but I believe it could be done with just three nodes (seen below).

I may be missing something however.

Much more elegant.

Div and round nodes

Even more elegant!

Based on the code I found on next link, you can round up or down to the closest multiple:
Code link: Round the given number to nearest multiple of 10 - GeeksforGeeks

# Python3 code to round the given

# integer to a whole number

# which ends with zero.

# function to round the number

def round ( n ):

# Smaller multiple

a = (n / / 10 ) * 10

# Larger multiple

b = a + 10

# Return of closest of two

return (b if n - a > b - n else a)

# driver code

n = 4722

print ( round (n))

# This code is contributed by "Sharad_Bhardwaj".

This is all you need to do (n is the number and m is the multiple); works with decimals, too:
image

2 Likes

Here is how I made it. Hope it helps someone !

1 Like

If you can make it an float you can just divide/round/multiply.

3 Likes

Maybe i am missing something, but would thos whole rounding to a constant not just be like snapping to grid? Whatever you would feed into a snap to grid node, would become your constant, and every value gets snapped to the closest multiple of that.

6 Likes

Perfect for what I needed to do!

This was the easiest/best solution for me, thank you!