0

Ok, how do I round a decimal to the 2nd decimal place instead of just the first decimal place? I had to create a menu, where the "customer" orders food and we had to have the subtotal and tax and tip included. My code works fine unless the grand total is something like $3.8 when it should be $3.80. How can I fix that by only using Math.round()? My code for the money part of the menu is

    double SUBtotal = subTotal * 100.00;
    System.out.println("Your current total is: $" + 
    Math.round(SUBtotal)/100.00); 
    System.out.println("Options:");
    System.out.println(" 1. Order another item");
    System.out.println(" 2. Checkout");

        mainOp = scan.nextInt();
       if (mainOp==2)
    {

        System.out.println(Order);

        double tax = subTotal * 0.0825;
        double taxSubtotal = tax + subTotal;
        double please = taxSubtotal * 100.00;
        double taxSubtotal2 = Math.round(please) / 100.00;
        System.out.println("\nSubtotal (with tax): $ " + taxSubtotal2);

        System.out.println("Tip: $");
        double tip = scan.nextDouble();
        double total = taxSubtotal + tip;
        double total2 = total * 100.00;
        double total3 = Math.round(total2) /100.00;
        System.out.println("Final Total: $" + total3);

        System.out.println();

        System.out.println("Thank You For Ordering!");


    }

Thank you very much!

LW001
  • 1,812
  • 4
  • 19
  • 28

2 Answers2

1

Here is a small code snippet using DecimalFormat to solve your problem.

DecimalFormat decimalFormat = new DecimalFormat("#0.00");
System.out.println(decimalFormat.format(total3));

This will print your decimal value as a string having two decimal places appended. Additionally, you can declare one decimalFormat variable and use it through out your code everywhere, wherever you want to display a 2 decimal place value.

Thanks

Safeer Ansari
  • 742
  • 4
  • 12
  • Doesn't seem to work because BlueJ doesn't seem to recognize "DecimalFormat," Is there any way to use a case/if statement with Math.round() or something along the lines like that? – Ishaan Mehta Nov 23 '17 at 16:34
0

If you want to 3.80 instead of 3.8, use below code after getting total. String is that is you want.

DecimalFormat f = new DecimalFormat("##.00");

String d = f.format(taxSubtotal2);