Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,849 questions

55,678 answers

573 users

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 May 29 by avibootz
...