How to calculate the percentage change between two values in C#

1 Answer

0 votes
using System;

class Program
{
    static double PercentageChange(double oldValue, double newValue) {
        if (oldValue == 0.0)
            throw new ArgumentException("oldValue cannot be zero");

        return ((newValue - oldValue) / oldValue) * 100.0;
    }

    static void Main()
    {
        double oldValue = 45.0;
        double newValue = 57.0;

        try
        {
            double change = PercentageChange(oldValue, newValue);
            Console.WriteLine($"Percentage change: {change:F2}%");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}



/*
run:

Percentage change: 26.67%

*/

 



answered Mar 16 by avibootz
...