3

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 2
    have you tried something? – stinepike Feb 24 '14 at 10:10
  • @StinePike Im new to Java so am unsure on the ways. I looked on the internet but a lot of replies are for decimals or involve rather long ways. I was wondering if there is a simple way to do such a thing? –  Feb 24 '14 at 10:12
  • 1
    ok .. it is definitely not bad to ask questions .. but here people like to see what you have tried so far.. it is better to correct your mistakes instead of providing the full answer :) – stinepike Feb 24 '14 at 10:14
  • @StinePike Thanks for that :) You may be able to tell but I joined this yesterday and am still understanding how it all works. Thanks for your advice –  Feb 24 '14 at 10:16

3 Answers3

10

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

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;
Bart van Nierop
  • 4,130
  • 2
  • 28
  • 32
0
  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);
}
Keppil
  • 45,603
  • 8
  • 97
  • 119