Home > Blockchain >  C# - Get X percent of Y dynamically
C# - Get X percent of Y dynamically

Time:10-15

I've trying to calculate what is X% of Y, although I'm getting mixed results.

I've tried the following equations:

return (percent / i) * 100; // Gives 0 for 200.GetPercent(10)
return percent * 100 / i; // Gives 5 for 200.GetPercent(10)

For method:

public static int GetPercent(this int i, int percent)
{
    return percent * 100 / i;
}

But none are giving me 20 back for 200.GetPercent(10)

CodePudding user response:

I believe this is the correct equation: Y * X / 100

public static int GetPercent(this int i, int percent)
{
    return (i * percent) / 100;
}

CodePudding user response:

Percentages are better dealt with using a a floating point type, here is a version using double with another parameter to set precision

public static double GetPercent(this int i, double percent, int precision) => 
    Math.Round(((i * percent) / 100), precision);

You can also define precision as an optional parameter, to give it a default value with int precision = n (n being an int of your choice)

public static double GetPercent(this int i, double percent, int precision = 2) => 
    Math.Round(((i * percent) / 100), precision);

200.GetPercent(10, 4); //precision = 4
200.GetPercent(10); //precision defaults to = 2
  •  Tags:  
  • c#
  • Related