To find out if the number divides evenly, check other answers, Modulo (%) is a way to do this.
To do what you want to do above, you do not need a loop:
public int nearestDivider(final int input) { final int multiple = input / 16;
This will return 48 if you give it 50, as your example.
If you really want the closest, you will need to do some floating point separation
public int nearestDivider(final int input) { final int multiple = Math.round((float) input / 16); return multiple * 16; }
Now 46 returns 48, 149 returns 144, etc.
xbakesx
source share