Reputation: 1449
To illustrate, I'd like to find out what the best way is to round the following integers:
(integer) -> (rounded value)
9 -> 100
200 -> 200
201 -> 300
1367 -> 1400
...so on and so forth... any suggestions on what would be the best way to accomplish this using Java?
Upvotes: 1
Views: 1568
Reputation: 51711
Using Math#ceil()
int[] ints = {9, 200, 201, 1367, 90210};
int[] rounded = new int[5];
for (int i = 0; i < ints.length; i++) {
rounded[i] = (int) (Math.ceil(ints[i]/100f) * 100f);
}
// prints: [100, 200, 300, 1400, 90300]
System.out.println(Arrays.toString(rounded));
Upvotes: 0
Reputation: 223043
public static int ceil100(int num) {
return (num + 99) / 100 * 100;
}
Granted, not efficient, but still. The answers posted by others work too:
public static int ceil100(int num) {
return num + 100 - num % 100;
}
Upvotes: 0
Reputation: 10810
Determine the modulus by 100
int k = 1234;
int mod = k % 100; //mod = 34
int difference = 100 - mod; //difference = 66
k += difference;
Straightforward.
Upvotes: 3