How to calculate the percentage change between two values in Scala

1 Answer

0 votes
object PercentageChangeApp {

  def percentageChange(oldValue: Double, newValue: Double): Double = {
    require(oldValue != 0.0, "oldValue cannot be zero")
    ((newValue - oldValue) / oldValue) * 100.0
  }

  def main(args: Array[String]): Unit = {
    val oldValue = 45.0
    val newValue = 57.0

    try {
      val change = percentageChange(oldValue, newValue)
      println(f"Percentage change: $change%.2f%%")
    } catch {
      case ex: IllegalArgumentException =>
        println(s"Error: ${ex.getMessage}")
    }
  }
}




/*
run:

Percentage change: 26.67%

*/

 



answered Mar 16 by avibootz
...