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

1 Answer

0 votes
import java.math.{BigDecimal, RoundingMode}
import java.text.NumberFormat

object CalculationDiscountTaxAndTotalWithBigDecimal_Scala {
  
  def main(args: Array[String]): Unit = {
    
    val amount: Double = 15745.723
    val discount: Double = 0.3
    
    var decimalAmount = BigDecimal(amount).setScale(2, RoundingMode.HALF_UP)
    val decimalDiscount = BigDecimal(discount)
    
    var discountAmount = decimalAmount.multiply(decimalDiscount).setScale(2, RoundingMode.HALF_UP)
    
    val totalBeforeTax = decimalAmount.subtract(discountAmount)
    val tax = BigDecimal(0.15)
    var taxAmount = tax.multiply(totalBeforeTax).setScale(2, RoundingMode.HALF_UP)
    val total = totalBeforeTax.add(taxAmount)
    
    val currency = NumberFormat.getCurrencyInstance()
    val percent = NumberFormat.getPercentInstance()
    
    val message = s"Amount: ${currency.format(decimalAmount)}\n" +
                  s"Discount: ${percent.format(decimalDiscount)}\n" +
                  s"Discount amount: ${currency.format(discountAmount)}\n" +
                  s"Total before tax: ${currency.format(totalBeforeTax)}\n" +
                  s"Tax amount: ${currency.format(taxAmount)}\n" +
                  s"Total: ${currency.format(total)}\n"
    
    println(message)
  }
}


/*
run:

Amount: $15,745.72
Discount: 30%
Discount amount: $4,723.72
Total before tax: $11,022.00
Tax amount: $1,653.30
Total: $12,675.30

*/



 



answered Sep 19, 2024 by avibootz
...