Reputation:
How do you round an integer to the closest 100? For example, 497 would round to 500, 98 would round to 100, and 1423 would round to 1400.
Upvotes: 3
Views: 5165
Reputation: 311458
I'd divide by 100, round, and then multiply again:
int initial = ...;
int rounded = (int) Math.round(initial/100.0) * 100;
Note to divide by 100.0
and not 100
, so you do the division in floating point arithmetic.
Upvotes: 11
Reputation: 4350
Another way, that avoids floating point arithmetic and possible precision errors is something along these lines:
int value = 497;
int rounded = 0;
int remainder = value % 100;
if (remainder >= 50) {
rounded = value - remainder + 100;
} else {
rounded = value - remainder;
}
or simpler:
int rounded = ((value + 50) / 100) * 100;
Upvotes: 2
Reputation: 46219
Small demo:
int[] values = { 497, 98, 1423 };
for (int value : values) {
int rounded = (int) Math.round(value / 100.0) * 100;
System.out.format("Before: %4d Rounded: %4d%n", value, rounded);
}
Upvotes: 0