How to calculate the percentage change between two values in Java

1 Answer

0 votes
public class PercentageChangeProgram {

    public static double percentageChange(double oldValue, double newValue) {
        if (oldValue == 0.0) {
            throw new IllegalArgumentException("oldValue cannot be zero");
        }
        return ((newValue - oldValue) / oldValue) * 100.0;
    }

    public static void main(String[] args) {
        double oldValue = 45.0;
        double newValue = 57.0;

        try {
            double change = percentageChange(oldValue, newValue);
            System.out.printf("Percentage change: %.2f%%%n", change);
        } catch (IllegalArgumentException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}


/*
run:

Percentage change: 26.67%

*/

 



answered Mar 16 by avibootz
...