Java Reference
In-Depth Information
lembeforeperforminganothercalculation, main() calls discount 's setScale()
method with these arguments:
2 : Two digits after the decimal point
RoundingMode.HALF_UP : The conventional approach to rounding
After setting the scale and proper rounding mode, main() subtracts discount
from invoiceSubtotal ,andassignstheresulting BigDecimal instanceto sub-
totalBeforeTax . main() calls setScale() on subtotalBeforeTax to
properly round its value before moving on to the next calculation.
main() next creates a BigDecimal object named salesTaxPercent that is
initialized to 0.05 . It then multiplies subtotalBeforeTax by salesTaxPer-
cent , assigning the result to salesTax , and calls setScale() on this
BigDecimal object to properly round its value.
Movingon, main() adds salesTax to subtotalBeforeTax ,savingtheresult
in invoiceTotal ,androundstheresultvia setScale() .Thevaluesintheseob-
jects are sent to the standard output device via System.out.println() , which
callstheir toString() methodstoreturnstringrepresentationsofthe BigDecimal
Whenyourunthisnewversionof InvoiceCalc ,youwilldiscoverthefollowing
Subtotal: 285.36
Discount: 28.54
SubTotal after discount: 256.82
Sales Tax: 12.84
Total: 269.66
Caution BigDecimal declaresa BigDecimal(double val) constructorthat
youshouldavoidusingifatallpossible.Thisconstructorinitializesthe BigDecim-
al instance to the value stored in val , making it possible for this instance to reflect
an invalid representation when the double value cannot be stored exactly. For ex-
ample, BigDecimal(0.1) results in
being stored in the instance. In contrast, BigDecimal("0.1") stores 0.1 exactly.
Search WWH ::

Custom Search