简体   繁体   English

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

[英]How to express “1.275” to “1.28” with Decimal Format in Java

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

Why are they different? 他们为什么不同?

The value of 63.275 is recorded in computer as 63.27499999999999857891452847979962825775146484375 . 计算机中记录的值为63.275,为63.27499999999999857891452847979962825775146484375。 As per the Java API doc " https://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html#HALF_UP " Behaves as for RoundingMode.UP if the discarded fraction is ≥ 0.5; 根据Java API文档“ https://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html#HALF_UP ”如果丢弃的分数≥0.5,则表现为RoundingMode.UP; otherwise, behaves as for RoundingMode.DOWN. 否则,表现为RoundingMode.DOWN。 so , 所以,

63.27499999999999857891452847979962825775146484375 ~ 63.27
64.275000000000005684341886080801486968994140625 ~ 64.28
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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM