Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OverflowException thrown when computing a percentage

I have code that takes as an argument a Dictionary and returns a Dictionary.

The code computes the sum of all the double values and uses the sum to compute what percentage each value is of the sum. It returns a new Dictionary with the percentages concatenated onto the keys.

There are some OverflowExceptions recorded in my web server's Event Viewer. The log records that the exception occurs on the following code Decimal percentage = (Decimal) (pDataPoints[key] / sum * 100); It says that the exception occurs when casting the value to a decimal.

What edge case could I be missing?

public static Dictionary<string, double> addPercentagesToDataPointLabels(Dictionary<string, double> pDataPoints)
{
Dictionary<string, double> valuesToReturn = new Dictionary<string, double>();

// First, compute the sum of the data point values
double sum = 0;
foreach (double d in pDataPoints.Values)
{
    sum += d;
}

// Now, compute the percentages using the sum and add them to the new labels.
foreach (string key in pDataPoints.Keys)
{
    string newKey = key;
    Decimal percentage = (Decimal) (pDataPoints[key] / sum * 100);
    percentage = Math.Round(percentage, ChartingValues.DIGITS_AFTER_DECIMAL_POINT);
    newKey += " " + percentage.ToString() + "%";
    valuesToReturn.Add(newKey, pDataPoints[key]);
}

return valuesToReturn;
}
like image 622
Vivian River Avatar asked Dec 28 '22 01:12

Vivian River


1 Answers

Here you go:

addPercentagesToDataPointLabels(new Dictionary<string, double>(){{"a", 0}});

Like gdoron said, you divide by 0. But it throws an exception only for ints. For floating point numbers, it results in Double.Infinity. It then tries to convert infinity to decimal.

like image 193
Euphoric Avatar answered Jan 11 '23 16:01

Euphoric