Calculating number needed to reach a certain percentage

Viewed 120

I'm trying to write a function that will tell me how many more is needed to reach a certain percentage.

This is the function I've gotten so far:

private static int CalculateHowManyNeeded(int TotalPallets, int PalletsDelivered, int MinReqPercentage = 25)
{
    return Convert.ToInt32((MinReqPercentage / 100.00 * TotalPallets) - PalletsDelivered);
}

However, my method fails to give me the right answer if I have TotalPallets = 2, and palletsDelivered = 0. I'm expecting to get 1.. but my method returns 0...

What is the best way I can fix this problem?

3 Answers

Convert.ToInt32 as written in the docs will return next:

value, rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

So in case of 0.5 you will get 0. Next depended on desired output, if you want to round also this halfway points to the "upper bound" you can use Math.Round with MidpointRounding.AwayFromZero (round to nearest mode: when a number is halfway between two others, it is rounded toward the nearest number that is away from zero.):

private static int CalculateHowManyNeeded(int TotalPallets, int PalletsDelivered, int MinReqPercentage = 25)
{
    return (int)Math.Round((MinReqPercentage / 100.00 * TotalPallets) - PalletsDelivered, MidpointRounding.AwayFromZero);
}

If you want to get the smallest integral value greater than or equal to the specified number (i.e. 1 for 0.1, 0.2 etc.) the you can use Math.Ceiling as @Harsh suggested in his answer.

I believe this is all you need -

    private static int CalculateHowManyNeeded(int TotalPallets, int PalletsDelivered, int MinReqPercentage = 25)
    {
        return (int) Math.Ceiling(MinReqPercentage * 0.01 * TotalPallets) - PalletsDelivered;
    }

Do the following output look good to you -

Console.WriteLine(CalculateHowManyNeeded(2, 0));     // 1
Console.WriteLine(CalculateHowManyNeeded(2, 1, 49)); // 0
Console.WriteLine(CalculateHowManyNeeded(2, 1, 50)); // 0
Console.WriteLine(CalculateHowManyNeeded(2, 1, 51)); // 1

I suggest you try something like this:

private static int CalculateHowManyNeeded(int TotalPallets, int PalletsDelivered, int MinReqPercentage = 25)
{
    int result =  Convert.ToInt32((MinReqPercentage / 100.00 * TotalPallets) - PalletsDelivered);
    result = result <= 0 ? 1 : result;
    return result;
}
Related