Reputation: 2535
I have the following function:
public static void main(String[] args) {
int interval = 23950;
System.out.println (Math.round(weekInterval/1000.00)*1000);
}
All the function does is rounding off the number (interval) to its nearest multiple of hundred or thousand etc.
Now the number interval is subject to change, it can vary from ranging between hundreds to billions, I want to set a general rule for division:
so that
Math.round(weekInterval/placeholder)*placeholder)
Any Ideas?
So far this is what I have come up with, using my limited knowledge -- bear with me this might be inefficient:
public static void main(String[] args) {
int weekInterval = 2500;
StringBuilder sbr = new StringBuilder();
int len = String.valueOf(weekInterval).length();
String num = "1";
for(int i = 2; i<=len; i++){
sbr.append("0");
}
System.out.println("Number is "+sbr.toString());
System.out.println("Number is "+num+sbr.toString());
int placeholder = Integer.valueOf(num+sbr.toString());
System.out.println((weekInterval + placeholder/2)/placeholder*placeholder);
}
Upvotes: 0
Views: 99
Reputation: 2248
A much easier solution using BigDecimal:
BigDecimal interval = new BigDecimal("8953315756233454365754734");
System.out.printf("%.0f\n",interval.round(new MathContext(1, RoundingMode.HALF_UP)));
Upvotes: 0
Reputation: 7921
From http://mindprod.com/jgloss/round.html#MULTIPLE:
// rounding m up to next highest multiple of n
int ceil = ( m + n - 1 ) / n * n;
// rounding m down to multiple of n
int floor = m / n * n;
// rounding m to nearest multiple of n
int near = ( m + n/2 ) / n * n;
Here m is the number to round and n would be your 'placeholder'
Upvotes: 1