Java Reference
In-Depth Information
LISTING 3.4
continued
{
final double
TAX_RATE = 0.06;
// 6% sales tax
int
quantity;
double
subtotal, tax, totalCost, unitPrice;
Scanner scan =
new
Scanner (System.in);
NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
NumberFormat fmt2 = NumberFormat.getPercentInstance();
System.out.print ("Enter the quantity: ");
quantity = scan.nextInt();
System.out.print ("Enter the unit price: ");
unitPrice = scan.nextDouble();
subtotal = quantity * unitPrice;
tax = subtotal * TAX_RATE;
totalCost = subtotal + tax;
// Print output with appropriate formatting
System.out.println ("Subtotal: " + fmt1.format(subtotal));
System.out.println ("Tax: " + fmt1.format(tax) + " at "
+ fmt2.format(TAX_RATE));
System.out.println ("Total: " + fmt1.format(totalCost));
}
}
OUTPUT
Enter the quantity:
5
Enter the unit price:
3.87
Subtotal: $19.35
Tax: $1.16 at 6%
Total: $20.51
Unlike the
NumberFormat
class, the
DecimalFormat
class is instantiated in
the traditional way using the
new
operator. Its constructor takes a string that
represents the pattern that will guide the formatting process. We can then use the
Search WWH ::
Custom Search