How do you round an integer to the closest 100? For example 497 would round to 500, 98 round to 100, 1423 round to 1400.

有帮助吗?

解决方案

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.

其他提示

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;
  1. Divide by 100
  2. Round
  3. Multiply by 100

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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top