【问题标题】:DecimalFormat newFormat = new DecimalFormat("##.##");DecimalFormat newFormat = new DecimalFormat("##.##");
【发布时间】:2018-02-14 05:21:59
【问题描述】:

DecimalFormat newFormat = new DecimalFormat("##.##"); 给我以下值的意外结果:

for value 0.005 = 0.00
          0.015 = 0.02

DecimalFormat 未格式化 0.005 to 0.01。当提供DecimalFormat newFormat = new DecimalFormat("##.##"); 时,请告诉我如何获取0.005 to 0.01 的值。

提前致谢。

【问题讨论】:

  • 使用 Match.round(val) 然后应用 DecimalFormat
  • 添加你目前尝试过的代码。
  • 双 d= 0.005; DecimalFormat newFormat = new DecimalFormat("#.##"); double twoDecimal = Double.parseDouble(newFormat.format(d)); System.out.println(twoDecimal);

标签: java decimal


【解决方案1】:

看完你的评论,你可以手动四舍五入到2位再做十进制格式。

示例如下:

public static void main(String[] args) {
    double input = 0.004;
    DecimalFormat formatter = getDecimalFormat(input); 
    System.out.println(formatter.format(round2Digit(input)));
    input = 0.005;
    formatter = getDecimalFormat(input); 
    System.out.println(formatter.format(round2Digit(input)));
    input = 0.015;
    formatter = getDecimalFormat(input); 
    System.out.println(formatter.format(round2Digit(input)));
}

private static DecimalFormat getDecimalFormat(double input){
    DecimalFormat formatter = (input % 1 == 0) ? new DecimalFormat("##.##"): new DecimalFormat("#0.00"); 
    return formatter;
}

private static double round2Digit(double input){
    double result = input * 100;
    result = Math.round(result);
    result = result / 100;
    return result;
}

输出:

0.00

0.01

0.02

【讨论】:

  • 如果我们使用 roundingMode.Up 它将输出 0.004 作为 0.001。
  • 你现在可以检查答案吗?
  • 感谢您的回答。如果可能的话,请告诉我为什么 DecimalFormat 会这样?
  • 默认 DecimalFormat 使用 RoundingMode.HALF_EVEN。它向“最近的邻居”四舍五入,除非两个邻居是等距的,在这种情况下,向偶数邻居四舍五入。您可以参考stackoverflow.com/questions/28134938/… 了解更多信息。
猜你喜欢
  • 1970-01-01
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多