Java Reference
In-Depth Information
PerhapsyouarewonderingwhyIdidnotdeclare balance tobeoftype double or
float .Thatway, balance couldstorevaluessuchas18.26(18dollarsinthewhole
number part and 26 pennies in the fraction part). I did not declare balance to be a
double or float for the following reasons:
• Notallfloating-pointvaluesthatcanrepresentmonetaryamounts(dollarsand
cents) can be stored exactly in memory. For example, 0.1 (which you might
usetorepresent10cents)hasnoexactstoragerepresentation. Ifyouexecuted
double total = 0.1; for (int i = 0; i < 50; i++)
total += 0.1; System.out.println(total); ,youwouldobserve
5.099999999999998 instead of the correct 5.1 as the output.
• Theresultofeachfloating-pointcalculationneedstoberoundedtothenearest
ferfromthecorrectresult.Although Math suppliesapairof round() meth-
ods that you might consider using to round a calculation to the nearest cent,
these methods round to the nearest integer (dollar).
Listing4-31 ' s InvoiceCalc applicationdemonstratesbothproblems.However,the
Listing 4-31. Floating-point-based invoice calculations leading to confusing results
import java.text.NumberFormat;
class InvoiceCalc
final static double DISCOUNT_PERCENT = 0.1; // 10%
final static double TAX_PERCENT = 0.05; // 5%
public static void main(String[] args)
double invoiceSubtotal = 285.36;
double discount = invoiceSubtotal*DISCOUNT_PERCENT;
double subtotalBeforeTax = invoiceSubtotal-discount;
double salesTax = subtotalBeforeTax*TAX_PERCENT;
double invoiceTotal = subtotalBeforeTax+salesTax;
Search WWH ::

Custom Search