How to calculate % change from X to Y in C#

1 Answer

0 votes
using System;

class PercentChangeProgram
{
    static double PercentChange(double x, double y) {
        return ((y - x) / Math.Abs(x)) * 100.0;
    }

    static string DescribeChange(double x, double y) {
        double pct = PercentChange(x, y);

        if (pct > 0) {
            return string.Format(
                "From {0:F1} to {1:F1} is a {2:F2}% increase (+{2:F2}%)",
                x, y, pct
            );
        }
        else if (pct < 0) {
            return string.Format(
                "From {0:F1} to {1:F1} is a {2:F2}% decrease ({3:F2}%)",
                x, y, Math.Abs(pct), pct
            );
        }
        else {
            return string.Format(
                "From {0:F1} to {1:F1} is no change",
                x, y
            );
        }
    }

    static void Main()
    {
        Console.WriteLine(DescribeChange(-80.0, 120.0));
        Console.WriteLine(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 May 29 by avibootz
...