user7327674
user7327674

Reputation: 27

Rounding an int number to another int number

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

Upvotes: 1

Views: 270

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198023

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.)

Upvotes: 3

Jonny Henly
Jonny Henly

Reputation: 4213

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

Upvotes: 2

Mureinik
Mureinik

Reputation: 311163

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);
}

Upvotes: 5

Related Questions