How to calculate % change from X to Y in Scala

1 Answer

0 votes
object PercentChangeDemo {

  def percentChange(x: Double, y: Double): Double =
    ((y - x) / math.abs(x)) * 100.0

  def describeChange(x: Double, y: Double): String = {
    val pct = percentChange(x, y)

    pct match {
      case p if p > 0 =>
        f"From $x%.1f to $y%.1f is a $p%.2f%% increase (+$p%.2f%%)"

      case p if p < 0 =>
        f"From $x%.1f to $y%.1f is a ${math.abs(p)}%.2f%% decrease ($p%.2f%%)"

      case _ =>
        f"From $x%.1f to $y%.1f is no change"
    }
  }

  def main(args: Array[String]): Unit = {
    println(describeChange(-80.0, 120.0))
    println(describeChange(120.0, 30.0))
    println(describeChange(60.0, 60.0))
  }
}



/*
run:

From -80.0 to 120.0 is a 250.00% increase (+250.00%)
From 120.0 to 30.0 is a 75.00% decrease (-75.00%)
From 60.0 to 60.0 is no change

*/

 



answered 41 minutes ago by avibootz
...