1
while(potatosconeflour <= c1) { potatosconeflour = potatosconeflour + potatosconeflour; } 

I used a while loop which does not work after inputting the number 24.I am trying to round an int number to another int number. E.g., I want to round any number to a multiple of 8.

E.g: rounding 1 to 8, 13 to 16, 23 to 24

1
  • Hello and welcome to stackoverflow! Please show us some more of your code - the current excerpt isn't sufficient to find the problem. Commented Dec 21, 2016 at 21:27

3 Answers 3

5

I'd divide the source number by the number to round it by (caution: cast it to a double so you don't use integer division!) use Math.ceil to round the result upwards, and then multiply it back by the same number:

public static int roundToMultiple(int toRound, int roundBy) { return roundBy * (int) Math.ceil((double)toRound / roundBy); } 
Sign up to request clarification or add additional context in comments.

3 Comments

This is wrong. You can't use Math.round, roundToMultiple(1,8) will return 0
Math.round rounds to the nearest int, so 1/8 will get rounded to 0 and then 0 * 8 = 0. You need to use Math.ceil instead
@Marcelo you're right. The OP used the term round, although he actually meant ceiling, which threw me off. I've edited my answer accordingly.
3

If you want to round to the nearest multiple of 8, that's just ((i + 3) / 8) * 8. (That rounds down if it's 8n + 4. If you want to round up from half, use i + 4 instead of i + 3. If you want to round "all the way up," 9 to 16, use i + 7.)

2 Comments

thanks for your help. what would i use if i wanted to round to a multiple of 225
In general it's just ((i + (n/2)) / n) * n.
2

Use the modulo operator (%), which returns the remainder, then add the subtraction of the remainder from 8 to your number.

public static void main(String[] args) { int i = 13; int rem = i % 8 > 0 ? i % 8 : 8; i += 8 - rem; System.out.println(i); } 

Outputs: 16

3 Comments

Thanks for the help. however if i input the number 8 it rounds up to 16. how can i get it so the number 8 will stay on 8 and not round up to 16???
@user7327674 ahh I forgot to check if i was already a multiple of 8.
@user7327674 I updated my answer but it throws a conditional into the mix, your better off using Mureinik's answer or Louis Wasserman's answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.