How to calculate % change from X to Y in Rust

1 Answer

0 votes
use std::f64;

fn percent_change(x: f64, y: f64) -> f64 {
    ((y - x) / x.abs()) * 100.0
}

fn describe_change(x: f64, y: f64) -> String {
    let pct = percent_change(x, y);

    if pct > 0.0 {
        format!(
            "From {:.1} to {:.1} is a {:.2}% increase (+{:.2}%)",
            x, y, pct, pct
        )
    } else if pct < 0.0 {
        format!(
            "From {:.1} to {:.1} is a {:.2}% decrease ({:.2}%)",
            x, y, pct.abs(), pct
        )
    } else {
        format!("From {:.1} to {:.1} is no change", x, y)
    }
}

fn main() {
    println!("{}", describe_change(-80.0, 120.0));
    println!("{}", describe_change(120.0, 30.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%)

*/

 



answered May 29 by avibootz
...