【问题标题】:How to display a double with no leading zero before the decimal in Java如何在Java中显示小数点前没有前导零的双精度数
【发布时间】:2019-09-28 23:05:16
【问题描述】:

课堂作业:编写一个计算棒球运动员击球率的方法。我需要输出为 0.345,但我一直得到 0.345。如何格式化此输出,以便在小数点前不显示前导零?感谢您提供的任何帮助。

这是我的 BaseballPlayer 类中的代码:

//BaseballPlayer parameters

String name;
int number;
int singles;
int doubles;
int triples;
int homeRuns;
int atBats;
int walks;
int sacrificeFlies;

//DecimalFormat

static DecimalFormat df  =   new DecimalFormat(".000");

//BaseballPlayer constructor method

public BaseballPlayer(String name, int number, int singles, int triples, int homeRuns, int atBats, int walks, 
        int sacrificeFlies)
{
    this.name            =   name;
    this.number          =   number;
    this.singles         =   singles;
    this.triples         =   triples;
    this.homeRuns        =   homeRuns;
    this.atBats          =   atBats;
    this.walks           =   walks;
    this.sacrificeFlies  =   sacrificeFlies;
}

public double getBattingAverage()
{
     return Double.parseDouble(df.format( (double) ( singles + doubles + triples + homeRuns ) / atBats) );
}

这是我的主类中的代码:

BaseballPlayer player01  =   new BaseballPlayer( "Mr. Business",13,12,13,4,84,63,7);

    System.out.println(player01.getBattingAverage());

我的输出:

运行:

0.345

构建成功(总时间:0 秒)

【问题讨论】:

  • 您的代码 sn-p 没问题,问题出在代码的其他地方。也许发布您的输出结果的声明?
  • 感谢您的帮助。我在我的 BaseballPlayer 类和主类中发布了代码。

标签: java methods decimalformat


【解决方案1】:

您忘记格式化实际输出 - 您正在格式化进入 Double.parseDouble() 函数的值,而不是 getBattingAverage() 函数的实际结果,因此 System.out.println() 输出不是您所期望的。您的主要方法应如下所示:

public static void main(String[] args) {
    BaseballPlayer player01  =   new BaseballPlayer ( "Mr. Business",13,12,13,4,84,63,7);
    String str = df.format(player01.getBattingAverage());
    System.out.println(str);
}

如果要格式化实际的 getBattingAverage() 输出,则需要执行以下操作:

public String getBattingAverage() {
    Double average = Double.parseDouble(df.format( (double) ( singles + doubles + triples + homeRuns ) / atBats) );
    return df.format(average);
}

然后你的主要方法是这样的:

Main player01  =   new Main( "Mr. Business",13,12, 13,4,84,63,7);
System.out.println(player01.getBattingAverage());

在不相关的方面,我相信你忘记为你的 BaseballPlayer 设置双打......所以它总是 0。

【讨论】:

    【解决方案2】:

    这是一种方法。

          double[] vals = { 0.233, .229, .292
          };
          for (double v : vals) {
             System.out.println(String.format("%.3f", v).substring(1));
          }
    

    【讨论】:

    • 这是一个优雅的解决方案,只要数字是正数..如果你有一个负值它不起作用..
    • 击球率永远不会是负数。
    • 当然它们永远不会是负面的。但我的版本是通用的,适用于 + 或 - 值...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 2013-06-01
    • 1970-01-01
    相关资源
    最近更新 更多