How to calculate discount, tax, and total with BigDecimal in Java

1 Answer

0 votes
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
   
public class CalculationDiscountTaxAndTotalWithBigDecimal_Java  {
       
    public static void main(String[] args) {
          
        double amount = 12345.123;
        double discount = 0.3;
          
        BigDecimal decimalAmount = new BigDecimal(Double.toString(amount));
        decimalAmount = decimalAmount.setScale(2, RoundingMode.HALF_UP);
        BigDecimal decimalDiscount = new BigDecimal(Double.toString(discount));
  
        BigDecimal discountAmount = decimalAmount.multiply(decimalDiscount);
        discountAmount = discountAmount.setScale(2, RoundingMode.HALF_UP);
  
        BigDecimal totalBeforeTax = decimalAmount.subtract(discountAmount);
        BigDecimal tax = new BigDecimal(".15");
        BigDecimal taxAmount = tax.multiply(totalBeforeTax);
        taxAmount = taxAmount.setScale(2, RoundingMode.HALF_UP);
        BigDecimal total = totalBeforeTax.add(taxAmount);
  
        NumberFormat currency = NumberFormat.getCurrencyInstance();
        NumberFormat percent = NumberFormat.getPercentInstance();
  
        String message = "Amount: " + currency.format(decimalAmount) + "\n" + 
                         "Discount: " + percent.format(decimalDiscount) + "\n" +
                         "Discount amount: " + currency.format(discountAmount) + "\n" + 
                         "Total before tax: " + currency.format(totalBeforeTax) + "\n" + 
                         "Tax amount: " + currency.format(taxAmount) + "\n" + 
                         "Total: " + currency.format(total) + "\n";
  
        System.out.println(message);
    }
}
      
      
/*
run:
   
Amount: $12,345.12
Discount: 30%
Discount amount: $3,703.54
Total before tax: $8,641.58
Tax amount: $1,296.24
Total: $9,937.82
       
*/

 



answered Jan 24, 2016 by avibootz
edited Sep 19, 2024 by avibootz

Related questions

1 answer 106 views
1 answer 787 views
1 answer 220 views
1 answer 220 views
1 answer 140 views
1 answer 130 views
2 answers 124 views
...