Calculate Percent Increase and Decrease

X3074861X picture X3074861X · Nov 25, 2014 · Viewed 14.6k times · Source

I'm likely over-thinking this, but I'm looking for something a bit more elegant than what I currently have.

I have this method called CalculatePercentageTrend, which takes in a long "previous" value and "current" value. As it currently stands :

public static string CalculatePercentageTrend(long previousValue, long currentValue)
{
    var trend = "0.00%";

    // calculate percentage increase
    if (previousValue < currentValue)
    {
        if (previousValue != 0)
        {
            var difference = previousValue - currentValue;
            var pctDecrease = (double)(difference / previousValue) * 100;
            trend = pctDecrease.ToString("P");
        }
        else
        {
            trend = currentValue.ToString("P");
        }
     }
    // calculate percentage decrease
    else if (currentValue < previousValue)
    {
        if (previousValue != 0)
        {
            var difference = currentValue - previousValue;
            var pctIncrease = (double)(difference / previousValue) * 100;
            trend = pctIncrease.ToString("P");
        }
        else
        {
            trend = currentValue.ToString("P");
        }
    }
    return trend;
}

This feels very repetitive, and has a few short comings. Negative trends aren't calculated properly, as they always result in a 0.00% change - what would be great is if I could get a negative percentage IF in fact the previous value is greater than the current value.

Also, I'm handling any possible 0's before dividing, but I'm wondering if there's a better approach to that as well.

My Question :

How can I get negative percentages to calculate correctly, and how can I improve this code overall?

Answer

Michael picture Michael · Nov 25, 2014

You're way over thinking it.

double CalculateChange(long previous, long current)
{
    if (previous == 0)
        throw new InvalidOperationException();

    var change = current - previous;
    return (double)change / previous;
}

To display this data to a user in a friendly 'percentage' format, you can use:

string DoubleToPercentageString(double d)
{
    return "%" + (Math.Round(d, 2) * 100).ToString();
}