How to calculate % change from X to Y in Java

1 Answer

0 votes
public class PercentChangeProgram {

    public static double percentChange(double x, double y) {
        return ((y - x) / Math.abs(x)) * 100.0;
    }

    public static String describeChange(double x, double y) {
        double pct = percentChange(x, y);

        if (pct > 0) {
            return String.format(
                "From %.1f to %.1f is a %.2f%% increase (+%.2f%%)",
                x, y, pct, pct
            );
        } else if (pct < 0) {
            return String.format(
                "From %.1f to %.1f is a %.2f%% decrease (%.2f%%)",
                x, y, Math.abs(pct), pct
            );
        } else {
            return String.format(
                "From %.1f to %.1f is no change",
                x, y
            );
        }
    }

    public static void main(String[] args) {
        System.out.println(describeChange(-80.0, 120.0));
        System.out.println(describeChange(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 5 hours ago by avibootz
edited 5 hours ago by avibootz
...