<<< BigDecimal Rounding Demo | Index | MOST COMMON MISTAKE WITH BigDecimal >>> |
The import statement required for BigDecimal arithmetic is
import java.math.*; // imports all classes and
// enumerations in java.math
Sample calculation using BigDecimal:
// convert subtotal and discount percent to BigDecimal
double subtotal = 456.78;
double discountPercent = 0.2345;
final double SALES_TAX_PCT = 0.085;
BigDecimal decimalSubtotal =
new BigDecimal(Double.toString(subtotal));
decimalSubtotal =
decimalSubtotal.setScale(2, RoundingMode.HALF_UP);
BigDecimal decimalDiscountPercent =
new BigDecimal(Double.toString(discountPercent));
// calculate discount amount
BigDecimal discountAmount =
decimalSubtotal.multiply(decimalDiscountPercent);
discountAmount = discountAmount.setScale(
2, RoundingMode.HALF_UP);
// calculate total before tax, sales tax, and total
BigDecimal totalBeforeTax =
decimalSubtotal.subtract(discountAmount);
BigDecimal salesTaxPercent =
new BigDecimal(SALES_TAX_PCT);
BigDecimal salesTax =
salesTaxPercent.multiply(totalBeforeTax);
salesTax = salesTax.setScale(2, RoundingMode.HALF_UP);
BigDecimal total = totalBeforeTax.add(salesTax);
<<< BigDecimal Rounding Demo | Index | MOST COMMON MISTAKE WITH BigDecimal >>> |