-2

Bit of a silly one, but just to clarify I know I can format the output to a string and then format the string in a variety of ways to achieve this but I need the return value to stay as a double as it has multiple uses.

So basically I have a LinkedList that i am reading values in from that was formatted as a double when imported. I am then using the sum of these values to essentially calculate a total which I am using in a toString function and a couple of other places.

My issue is if there are trailing zeros they are trimed so the values is as small as possible. e.g: 3.50 -> 3.5, 0.00 -> 0.0 and so on.

public double totalCost(){
        double total = 0.00;
        for(Ingredient cost : ingredients){
            total += cost.ingredientCost();
        }
        return total;

The code above is the sum code.

public String toString(){
        return crust() + " pizza with " + toppings() + " and " + sauce() + ": $" + totalCost();
    }

And this is my toString function.

Any guidance would be awesome.

Shaido
  • 27,497
  • 23
  • 70
  • 73
  • So if you know how to format a double to a String, what are you actually asking? A double is just a number, so there's no such thing as "a double storing 3.5" and "a double storing 3.500" being somehow different. – Dawood ibn Kareem May 04 '17 at 20:37

1 Answers1

0

I think this will help you:

public String toString(){
    return crust() + " pizza with " + toppings() + " and " + sauce() + ": $" + String.format( "%.2f", totalCost());
}