How to calculation tax with BigDecimal in Java

1 Answer

0 votes
import java.math.BigDecimal;
import java.text.NumberFormat;
  
public class Example {
    public static void main(String[] args) {
         
        BigDecimal amount = new BigDecimal("10000.56");
        BigDecimal tax = new BigDecimal("0.15");
          
        BigDecimal salesTax = amount.multiply(tax);
        salesTax = salesTax.setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal total = amount.add(salesTax);
          
        NumberFormat currency = NumberFormat.getCurrencyInstance();
  
        String s = "Amount: " + currency.format(amount) + "\n" + 
                   "Tax: " + currency.format(salesTax) + 
                   "\n" + "Total: " + currency.format(total) + "\n";
  
        System.out.println(s);
    }
}
     
     
     
/*
run:
  
Amount: $10,000.56
Tax: $1,500.08
Total: $11,500.64
      
*/

 



answered Jan 24, 2016 by avibootz
edited Jun 1, 2024 by avibootz

Related questions

1 answer 1,411 views
1 answer 94 views
1 answer 122 views
1 answer 216 views
2 answers 121 views
1 answer 111 views
1 answer 93 views
93 views asked Jun 3, 2024 by avibootz
...