80 likes | 95 Vues
The need for BigDecimal. Tim McKenna Seneca@York. Why BigDecimal?. BigDecimal provides exact decimal values doubles only approximate decimals use BigDecimal for money and business calculations yes, doubles are easier no, you cannot use doubles. BigDecimal vs double.
E N D
The need for BigDecimal Tim McKenna Seneca@York
Why BigDecimal? • BigDecimal provides exact decimal values • doubles only approximate decimals • use BigDecimal for money and business calculations • yes, doubles are easier • no, you cannot use doubles
BigDecimal vs double • from an assignment that didn’t use BigDecimal…Type Vegan Survey Last Date RestaurantCode Y/N Amount Surveyed Name, LocationCF Y 3.59 2003-07-04 Blueberry Hill, YLMPlease enter survey amount (+ add, - subtract) > -3.59 Unable to subtract this amount -3.589999999999999857891452847979962825775146484375because there is only 3.589999999999999857891452847979962825775146484375 left!
If you don't believe me… • from the IBM computer scientist who wrote the new, improved BigDecimal class: Using Java 5.0 BigDecimaland Decimal Arithmetic FAQ • Core Java Technologies Tech Tips:The need for BigDecimal
The BigDecimal Class • 98.7% of numeric data in business applications has a predetermined number of decimals: • currency, exchange rates, unit costs, discounts, taxes • precision: digits in number including decimals • scale: number of decimal places • JDBC maps DB decimal fields to BigDecimal • BigD class provides control of rounding behaviour • Examples: PaySchedule.java, PaySchedule2.java, DontUseDouble.java
BigDecimal add & subtract • BigDecimal sum, difference, …; // note: immutable class • sum = addend.add(augend); // a = b + c • sum = sum.add(anotherBigDecimal); // a += d • difference = minuend.subtract(subtrahend); // a = b - c
BigDecimal multply & divide • import static java.math.RoundingMode.HALF_UP;// standard rounding, import the constant • BigDecimal product, quotient; // immutable • product = multiplicand.multiply(factor); • product = // round result to 2 decimalsproduct.setScale(2, HALF_UP); • product = // multiply and roundmultiplicand.multiply(factor).setScale(2, HALF_UP); • quotient = // round result to 2 decimalsdividend.divide(divisor, 2, HALF_UP);
BigDecimal comparisons • import static java.math.BigDecimal.ZERO; • payment.compareTo(interest) > 0"if payment is greater than interest " • principal.compareTo(payment) <= 0 "if principal is less than/equal to payment" • principal.compareTo(ZERO) == 0"if principal is equal to zero" • principal.equals(ZERO)…may not be what you mean. see API.