Thugstin Swagburn
Thugstin Swagburn

Reputation: 1

issues with java and printf and decimals

Code:

import java.util.Scanner;

public class sdusti00lab1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        double AA = 8.25;
        double CA = 6.50;
        double ACP = 9.00;
        double CPC = 6.25;

        int numA, numC;
        double numSP, numLP;
        Scanner keys = new Scanner(System.in);
        System.out.print(" enter number of adults ");
        numA = keys.nextInt();
        System.out.println(" enter number of children ");
        numC = keys.nextInt();
        System.out.println(" enter number of small popcorn");
        numSP = keys.nextDouble();
        System.out.println(" enter number of large popcorn");
        numLP = keys.nextDouble();
        double  AAddPrice = (numA*AA);
        double  CAddPrice = (numC*CA);
        double  ACPT = ((ACP*.094)*AA);
        double CPCT = ((CPC*.094)*CA);
        double SPTax = (ACP*.094);
        double LPTax = (CPC*.094);
        System.out.println("Adult admission "+"\t"+numA + "\t$" + AAddPrice);
        System.out.println("Child admission  "+"\t"+numC + "\t$" + CAddPrice);
        System.out.println("Adult popcorn  "+"\t\t"+ACP + "\t$" + ACPT);
        System.out.println("Child popcorn  "+"\t\t"+CPC + "\t$" + CPCT);
        System.out.println("Tax  "+"\t\t\t$"+ (SPTax + LPTax));
        System.out.println("Total "+"\t\t\t$"+(AAddPrice+CAddPrice+CPCT+ACPT) ); 
    }
}

I need to change the last 6 lines of code to produce a decimal that stops at the number second to the decimal, but I just don't know how to do that.

Upvotes: 0

Views: 39

Answers (2)

Shahid
Shahid

Reputation: 2330

Use System.out.printf or System.out.format to do this. Use %.2f for printing upto two decimal point.

System.out.printf("Adult admission \t%d\t$%.2f%n", numA, AAddPrice);

Upvotes: 1

GhostCat
GhostCat

Reputation: 140427

There are various ways to turn numbers (float, double, ..) into formatted Strings. Oracle has a nice overview worth studying.

The important aspect to understand here: that process works by you

A) specifying a format that describes how your output should look like

B) you calling a formatter with that format and the numbers to format

Upvotes: 0

Related Questions