|
Rounding
A Programming Pattern |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
truncated
by place)value - truncated and half of
place
/**
* Round an int value to a given place (i.e., power of 10).
*
* @param number The number to round
* @param place The place to round to (10, 100, 1000, etc...)
* @return The rounded value
*/
public static int round(int number, int place) {
int rounded, truncated;
truncated = (number / place) * place;
if ((number % place) >= (place / 2)) {
rounded = truncated + place;
} else {
rounded = truncated;
}
return rounded;
}
items = 526;
place = 10;
rounded = round(items, place);
(number/place)*place is
(526/10)*10 or 520
number % place is 6
place / 2 is 5520 + 10 or 530
exact = (1993 + 93);
decade = round(exact, 10);
century = round(exact, 100);
(number/place)*place is
(2086/100)*100 or 2000
num % place is 86
100 / 2 is 502000 + 100 or
2100