Java Reference
In-Depth Information
System.out.println("Subtotal:
"+cur-
rencyFormat.format(invoiceSubtotal));
System.out.println("Discount:
"+cur-
rencyFormat.format(discount));
System.out.println("SubTotal after discount: "+
cur-
rencyFormat.format(subtotalBeforeTax));
System.out.println("Sales
Tax:
"+cur-
rencyFormat.format(salesTax));
System.out.println("Total:
"+cur-
rencyFormat.format(invoiceTotal));
}
}
Listing4-31 reliesonthe NumberFormat class(locatedinthe java.text pack-
age) and its format() method to format a double precision floating-point value into
acurrency—Idiscuss NumberFormat intheInternationalizationsectionofAppendix
C. When you run InvoiceCalc , you will discover the following output:
Subtotal: $285.36
Discount: $28.54
SubTotal after discount: $256.82
Sales Tax: $12.84
Total: $269.67
This output reveals the correct subtotal, discount, subtotal after discount, and sales
tax.Incontrast,itincorrectlyreveals269.67insteadof269.66asthefinaltotal.Thecus-
tomerwillnotappreciatepayinganextrapenny,eventhough269.67isthecorrectvalue
according to the floating-point calculations:
Subtotal: 285.36
Discount: 28.536
SubTotal after discount: 256.824
Sales Tax: 12.8412
Total: 269.6652
Theproblemarisesfromnotroundingtheresultofeachcalculationtothenearestcent
beforeperformingthenextcalculation.Asaresult,the0.024in256.824and0.0012in
12.84 contribute to the final value, causing NumberFormat 's format() method to
round this value to 269.67.
Search WWH ::




Custom Search