Search Unity

Round number to nearest multiple of x

Discussion in 'Scripting' started by BubyMB, Jul 13, 2018.

  1. BubyMB

    BubyMB

    Joined:
    Jun 6, 2016
    Posts:
    140
    Hey guys, I'm trying to make a ui that clips to the nearest multiple of x; I am using a grid system where each cell is 75 and spacing is 10. So my thought was say the ui length was 100, and i wanted to clip to the nearest multiple, that would be 85. how would i do that? I'm completely stuck any help would be appreciated thanks.
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,196
    Will they always be integer values, or do you need to round floats?

    This is a simple approach for int. Rounds to the nearest multiple, rounding down.

    Code (CSharp):
    1. public void RoundToMultiple(int value, int roundTo) {
    2.     return (value / roundTo) * roundTo;
    3. }
     
    RedEarth likes this.
  3. BubyMB

    BubyMB

    Joined:
    Jun 6, 2016
    Posts:
    140
    Didnt even think of that. Quite simple. thanks.