B.B10
B.B10

Reputation: 171

Truncate double or add extra 0 to the decimal - Java

This might be a duplicate, but I cannot find any answers that work with my code.

I'm trying to truncate my results for a method(for calculating a fee) in Java. I then try to write the results to a text file, but it's not showing like it should. This is what I get and what I'd like it to return:

  1. Result of fee is 8.4, it should return 8.40
  2. Result of fee is 8.0, it should return 8.00

And so on... Any suggestions please?

This is my entire code for the method:

public Double calculateFee(Parcel pcl) {    
    // Get type of parcel (E, S or X)
    String typeOfParcel = pcl.getParcelID().substring(0,1);
    // Formula for calculating fee
    Double fee = (double) 1 + Math.floor(pcl.getVolume()/28000) + (pcl.getDays()-1);

    // apply a discount to parcels of type "S"
    if (typeOfParcel.equalsIgnoreCase("S")) {
        fee = fee * 0.9;
    }

    // apply a discount to parcels of type "X"
    else if (typeOfParcel.equalsIgnoreCase("X")) {
        fee = fee * 0.8; 
    } 

    // This is what I tried:
    // Tried also using #.##, but no result
    DecimalFormat decim = new DecimalFormat("0.00");
    fee = Double.parseDouble(decim.format(fee));

    return fee;     
} 

Upvotes: 0

Views: 2765

Answers (2)

aglassman
aglassman

Reputation: 2653

The problem here isn't that you are formatting it wrong. You are formatting your double using:

decim.format(fee);

Then, you parse this string, back into a Double, therefore losing your formatting:

Double.parseDouble(...

Just return a String rather than a Double, and don't use Double.parseDouble.

Upvotes: 1

Andy Thomas
Andy Thomas

Reputation: 86509

One way is to use String.format().

  Double fee = 8.0;
  String formattedDouble = String.format("%.2f", fee );

Note that a Double doesn't hold a formatted representation of its value.

Additional details about format strings are available here.

Upvotes: 2

Related Questions