设置除法的一般规则

时间:2014-06-23 09:48:59

标签: java integer-division

我有以下功能:

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


    }

2 个答案:

答案 0 :(得分:1)

来自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是您的&#39;占位符&#39;

答案 1 :(得分:0)

使用BigDecimal的更简单的解决方案:

       BigDecimal interval = new BigDecimal("8953315756233454365754734");
       System.out.printf("%.0f\n",interval.round(new MathContext(1, RoundingMode.HALF_UP)));