StaceyM
StaceyM

Reputation: 35

How to display a double with no leading zero before the decimal in Java

Class assignment: write a method to calculate the batting average of a baseball player. I need the output to be .345, but I keep getting 0.345. How do I format this output so no leading zeros before the decimal place are displayed? Thank you for any help offered.

This is the code in my BaseballPlayer class:

//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) );
}

This is the code in my main class:

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

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

My output:

run:

0.345

BUILD SUCCESSFUL (total time: 0 seconds)

Upvotes: 1

Views: 922

Answers (2)

WJS
WJS

Reputation: 40034

Here's one way to do it.

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

Upvotes: 1

vs97
vs97

Reputation: 5859

You are forgetting to format the actual output - you are formatting the value that goes into the Double.parseDouble() function, but not the actual result of the getBattingAverage() function, so the System.out.println() output is not what you expect. Your main method should look like:

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);
}

If you want to format the actual getBattingAverage() output, you need to do the following:

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

And your main method then is like this:

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

On a side unrelated note, I believe you are forgetting to set the doubles for your BaseballPlayer... So it will always be 0.

Upvotes: 2

Related Questions