如何用Java中的十进制格式表示“1.275”到“1.28”

时间:2017-04-29 04:07:52

标签: java rounding decimalformat

DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
decimalFormat.applyPattern(".00");

System.out.print(decimalFormat.format(63.275));
// output : 63.27

System.out.print(decimalFormat.format(64.275));
// output : 64.28

为什么他们不同?

2 个答案:

答案 0 :(得分:0)

63.275的值在计算机中记录为63.27499999999999857891452847979962825775146484375。根据Java API doc“https://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html#HALF_UP”如果丢弃的分数≥0.5,则表现为RoundingMode.UP;否则,表现为RoundingMode.DOWN。 所以,

63.27499999999999857891452847979962825775146484375 ~ 63.27
64.275000000000005684341886080801486968994140625 ~ 64.28

答案 1 :(得分:0)

public static double roundByPlace(double number, int scale){
    BigDecimal bigDecimal = BigDecimal.valueOf(number);
    String pattern = "0.";
    for(int i = 0; i<scale; i++){
        pattern = pattern+"0";
    }
    DecimalFormat decimalFormat = new DecimalFormat(pattern);
    decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
    double result = Double.parseDouble(decimalFormat.format(bigDecimal));
    return result;
}