如何实现上舍入到0.05

这个问题是上次去一家公司去面试的时候,把我给难住了的地方。

只能怪自己没有好好的学习ceil和floor的用法;

其实google了以下只需要简单的方法一句话就可以了;

如下:

private static void roundUpToZeroPZeroFive2(double input) {
    double output = 0;
    System.out.println("before round :" + input);

    output = Math.ceil(input*20)/20;
    System.out.println("after round :" + output);
}

还有一种笨方法:

public static BigDecimal roundTax(BigDecimal bd){  
    if(bd == null || BigDecimal.ZERO.compareTo(bd) == 1){  
        return BigDecimal.ZERO.setScale(2);  
    }  
    bd = bd.setScale(2,RoundingMode.HALF_UP);  
    String strBd = bd.toString();  
    String strLastBit = strBd.substring(strBd.length()-1,strBd.length());  
    BigDecimal bdTemp = BigDecimal.ZERO;  
    bdTemp.setScale(2);  
    int iLastBit = Integer.valueOf(strLastBit);  
    if(iLastBit%5 != 0){  
        bdTemp = BigDecimal.valueOf(iLastBit).divide(BigDecimal.valueOf(100));  
        bdTemp = bdTemp.multiply(BigDecimal.valueOf(-1));  
        bdTemp = bdTemp.add(iLastBit>5 ? new BigDecimal("0.1") : new BigDecimal("0.05"));  
    }  
    bd = bd.add(bdTemp);  
    return bd;  
} 

参见这里:

http://blog.csdn.net/daxiang12092205/article/details/37989071

http://stackoverflow.com/questions/6330852/round-off-decimal-value-up-to-
nearest-0-05-value

面试题目可以看这里:

http://blog.csdn.net/daxiang12092205/article/details/37938915