我有以下功能:
public static void main(String[] args) {
int interval = 23950;
System.out.println (Math.round(weekInterval/1000.00)*1000);
}
该函数所做的全部工作就是将数字(间隔)四舍五入到最接近的十万倍等。
现在,数字间隔可能会有所变化,它的范围可以从数百到数十亿不等,我想为划分设置一个一般规则:
以便
Math.round(weekInterval/placeholder)*placeholder)
有任何想法吗?
编辑:
到目前为止,这是我使用有限的知识得出的结果-忍受这可能效率很低:
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);
}
最佳答案
从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;
m是要舍入的数字,n是您的“占位符”