java - 错误: while trying to format decimal output in Java

标签 java decimalformat

我正在写this program作为学校的作业。该程序从用户那里获取“性别”和“年龄”形式的输入,并返回所有男性和/或女性的平均年龄。

该程序一直运行良好,直到我妈妈对其进行了测试,我们偶然发现了一个问题。如果万一用户输入了一些人,而他们的年龄总和不能被输入的人数整除,则输出将给出小数点后 15 位的答案。 例如,如果我输入 3 位年龄分别为 98、1 和 1 的男性,程序将 100 除以 3,得到输出:

33.333333333333336.

所以我去SO寻找这个问题的解决方案,并发现this我在我的程序中实现了如下所示,以便将答案减少到最多 3 个小数位:

/*
This method takes two values. The first value is divided by the second value to get the average. Then it trims the
answer to output a maximum of 3 decimal places in cases where decimals run amok.
*/
public static double average (double a, double b){
    double d = a/b;
    DecimalFormat df = new DecimalFormat("#.###");
    return Double.parseDouble(df.format(d));

我在程序的底部用它自己的方法编写了代码,我在第 76 和 77 行的 main 方法中调用了该代码:

// Here we calculate the average age of all the people and put them into their respective variable.
    double yAverage = average(yAge, men);
    double xAverage = average(xAge, women);

但是。我明白了error message当我尝试运行该程序时,我不明白错误消息。我尝试用谷歌搜索该错误,但一无所获。 请记住,我是初学者,我需要任何人都能给我的简单答案。 预先感谢您!

最佳答案

问题是 DecimalFormat尊重您的区域设置设置,根据您的语言设置格式化数字。

例如在美国英语中,结果是 33.333,但在德国英语中,结果是 33,333

但是,Double.parseDouble(String s)被硬编码为仅解析美国英语格式。

修复此问题的一些选项:

  • 不要对值进行四舍五入。 推荐

    在需要显示值的地方使用 DecimalFormat,但保持值本身的完整精度。

  • 强制DecimalFormat使用美国英语格式符号。

    DecimalFormat df = new DecimalFormat("#.###", DecimalFormatSymbols.getInstance(Locale.US));
    
  • 使用DecimalFormat重新解析该值。

    DecimalFormat df = new DecimalFormat("#.###");
    try {
        return df.parse(df.format(d)).doubleValue();
    } catch (ParseException e) {
        throw new AssertionError(e.toString(), e);
    }
    
  • 不要将字符串转换为四舍五入到小数点后 3 位。

    • 使用Math.round(double a) .

      return Math.round(d * 1000d) / 1000d;
      
    • 使用BigDecimal (并坚持下去)推荐

      return BigDecimal.valueOf(d).setScale(3, RoundingMode.HALF_UP);
      
    • 使用BigDecimal (暂时)

      return BigDecimal.valueOf(d).setScale(3, RoundingMode.HALF_UP).doubleValue();
      

关于java - 错误: while trying to format decimal output in Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60363962/

相关文章:

java - 计算时差错误

Javafx double 变量,具有两位小数

仅具有负指数的 Java DecimalFormat

java - Netbeans JAVA MYSQL DB 异常行为 - 关闭应用程序后无法检索数据 - JDBC 驱动程序

java - 针对现有耳朵运行时,Jacoco 出现 “IllegalStateException: Incompatible execution data for class in…” 异常

Java动态实现抽象方法

java - 呈现通过 JDBC 检索的表 - JAVA

java - 格式化 BigDecimal 后出现 StringIndexOutOfBoundsException

java - 货币小数分隔符不起作用

java - 在数字和小数之间插入自定义字符串 - Java DecimalFormat