Presentation is loading. Please wait.

Presentation is loading. Please wait.

The need for BigDecimal Tim McKenna Why BigDecimal? BigDecimal provides exact decimal values doubles only approximate decimals use BigDecimal.

Similar presentations


Presentation on theme: "The need for BigDecimal Tim McKenna Why BigDecimal? BigDecimal provides exact decimal values doubles only approximate decimals use BigDecimal."— Presentation transcript:

1 The need for BigDecimal Tim McKenna Seneca@York

2 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

3 BigDecimal vs double from an assignment that didn’t use BigDecimal… Type Vegan Survey Last Date Restaurant Code Y/N Amount Surveyed Name, Location CF Y 3.59 2003-07-04 Blueberry Hill, YLM Please enter survey amount (+ add, - subtract) > -3.59 Unable to subtract this amount - 3.589999999999999857891452847979962825775146484375 because there is only 3.589999999999999857891452847979962825775146484375 left!

4 If you don't believe me… from the IBM computer scientist who wrote the new, improved BigDecimal class: Using Java 5.0 BigDecimal and Decimal Arithmetic FAQUsing Java 5.0 BigDecimalDecimal Arithmetic FAQ Core Java Technologies Tech Tips: The need for BigDecimal The need for BigDecimal

5 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

6 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

7 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 decimals product.setScale(2, HALF_UP); product = // multiply and round multiplicand.multiply(factor).setScale(2, HALF_UP); quotient = // round result to 2 decimals dividend.divide(divisor, 2, HALF_UP);

8 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.


Download ppt "The need for BigDecimal Tim McKenna Why BigDecimal? BigDecimal provides exact decimal values doubles only approximate decimals use BigDecimal."

Similar presentations


Ads by Google