Java Reference
In-Depth Information
BigDecimal
invoiceSubtotal
=
new
BigDecim-
al("285.36");
BigDecimal discountPercent = new BigDecimal("0.10");
BigDecimal
discount
=
invoiceSub-
total.multiply(discountPercent);
discount
=
discount.setScale(2,
Roundin-
gMode.HALF_UP);
BigDecimal
subtotalBeforeTax
=
invoiceSub-
total.subtract(discount);
subtotalBeforeTax
=
subtotalBeforeTax.setScale(2,
RoundingMode.HALF_UP);
BigDecimal salesTaxPercent = new BigDecimal("0.05");
BigDecimal
salesTax
=
subtotalBe-
foreTax.multiply(salesTaxPercent);
salesTax
=
salesTax.setScale(2,
Roundin-
gMode.HALF_UP);
BigDecimal
invoiceTotal
=
subtotalBe-
invoiceTotal
=
invoiceTotal.setScale(2,
Roundin-
gMode.HALF_UP);
System.out.println("Subtotal: "+invoiceSubtotal);
System.out.println("Discount: "+discount);
System.out.println("SubTotal after discount: "+sub-
totalBeforeTax);
System.out.println("Sales Tax: "+salesTax);
System.out.println("Total: "+invoiceTotal);
}
}
main() methodfirstcreates BigDecimal objects invoiceSub-
total and discountPercent that are initialized to 285.36 and 0.10 , respect-
ively.Itthenmultiplies invoiceSubtotal by discountPercent andassignsthe
BigDecimal result to discount .
At this point, discount contains 28.5360. Apart from the trailing zero, this value
isthesameasthatgeneratedby invoiceSubtotal*DISCOUNT_PERCENT in List-
ing4-31 . Thevaluethatshouldbestoredin discount is28.54.Tocorrectthisprob-
Search WWH ::

Custom Search