0

I have a code where an individual orders a certain number of coffees and coffee shots in each cup, and the program calculates the total price (purchasePrice). However, when i output the purchase price as a double, it only outputs a number with 1 decimal place. How can i change it to output with 2 decimal places.

double purchasePrice = 0;
  for (counting = 0; counting < coffeeCups; counting++) {
    System.out.println("Cup " + (counting + 1) + " has " + coffeeShots[counting] + " shot(s) and will cost $" + (2 + coffeeShots[counting]) + "\n");
    purchasePrice+= 2 + (coffeeShots[counting]);
  }
  System.out.println(coffeeCups + " coffees to purchase.");
  System.out.println("\nPurchase price is $" + purchasePrice + ".");
Shahrokh Aryana
  • 49
  • 1
  • 2
  • 12

1 Answers1

1

Please refer to Decimal Format

// 2 places of decimal
DecimalFormat formatter = new DecimalFormat( "#.00" );

System.out.println(formatter.format(1.23));    // 1.23
System.out.println(formatter.format(1));       // 1.00
System.out.println(formatter.format(1.234));   // 1.23
Debosmit Ray
  • 5,228
  • 2
  • 27
  • 43
  • Whenever i try using DecimalFormat in my code it seems to be coming up with a compiler error that it cannot find the symbol of 'DecimalFormat' – Shahrokh Aryana Mar 29 '16 at 07:33
  • Well, you have to import the relevant class. I believe it is `java.text.DecimalFormat`. – Debosmit Ray Mar 29 '16 at 07:34
  • @ShahrokhAryana It would be nice, if you could accept/upvote an answer if your issue is resolved. From [here](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work), "Accepting an answer is important as it both rewards posters for solving your problem and informs others that your issue is resolved." – Debosmit Ray Mar 29 '16 at 07:37
  • Sorry @DebosmitRay, im brand new to StackOverflow and programming so its taking a bit of time to get used to. Thank you very much! – Shahrokh Aryana Mar 29 '16 at 07:39
  • @ShahrokhAryana Not a problem. Welcome to SO! :) – Debosmit Ray Mar 29 '16 at 07:39