user3344370
user3344370

Reputation:

Rounding to the closest 100

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

Answers (3)

Mureinik
Mureinik

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

Bart van Nierop
Bart van Nierop

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

Keppil
Keppil

Reputation: 46219

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

Upvotes: 0

Related Questions