X3074861X
X3074861X

Reputation: 3819

Calculate Percent Increase and Decrease

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?

Upvotes: 7

Views: 21998

Answers (3)

Sikandar Amla
Sikandar Amla

Reputation: 1475

I used following function with 100% accuracy.

    decimal CalculateChange(decimal previous, decimal current)
    {
        if (previous == 0)
            return 0;

        if (current == 0)
            return -100;

        var change = ((current - previous) / previous) * 100;

        return change;
    }

Upvotes: 6

Michael
Michael

Reputation: 1833

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();
}

Upvotes: 21

Hamid Pourjam
Hamid Pourjam

Reputation: 20764

I think this will resolve your issue, all you need is calculating the difference and it's ratio with respect to previous value.

public static string CalculatePercentageTrend(long previous, long current)
{
    return ((current - previous) / (double)previous).ToString("p");
}

Upvotes: 4

Related Questions