You can do:
private int getInventorySize(int max) {
if (max <= 0) return 9;
int quotient = (int)Math.ceil(max / 9.0);
return quotient > 5 ? 54: quotient * 9;
}
Divide the number by 9.0
. And taking the ceiling will get you the next integral quotient. If quotient is > 5
, then simply return 54
, else quotient * 9
will give you multiple of 9
for that quotient.
Some test cases:
// Negative number and 0
System.out.println(getInventorySize(-1)); // 9
System.out.println(getInventorySize(0)); // 9
// max <= 9
System.out.println(getInventorySize(5)); // 9
System.out.println(getInventorySize(9)); // 9
// some middle case
System.out.println(getInventorySize(43)); // 45
// max >= 54
System.out.println(getInventorySize(54)); // 54
System.out.println(getInventorySize(55)); // 54
10
solved rounding up a number to nearest 9