Percentage calculation

C#asp.netasp.net Mvc-2Drop Down-Menu

C# Problem Overview


I am working in progress bar concept in ASP.NET MVC 2. Here i have a DropDownList which has 10 values. i want to calculate the percentage for progress bar, e.g. 10 values from DropDownList and i am having a query which returns the value 2. so, out of 10 values i am getting 2. "20 % completed" should be displayed.. How to do this calculation

C# Solutions


Solution 1 - C#

Using Math.Round():

int percentComplete = (int)Math.Round((double)(100 * complete) / total);

or manually rounding:

int percentComplete = (int)(0.5f + ((100f * complete) / total));

Solution 2 - C#

(current / maximum) * 100. In your case, (2 / 10) * 100.

Solution 3 - C#

With C# String formatting you can avoid the multiplication by 100 as it will make the code shorter and cleaner especially because of less brackets and also the rounding up code can be avoided.

(current / maximum).ToString("0.00%");

// Output - 16.67%

Solution 4 - C#

Mathematically, to get percentage from two numbers:

percentage = (yourNumber / totalNumber) * 100;

And also, to calculate from a percentage :

number = (percentage / 100) * totalNumber;

Solution 5 - C#

You can hold onto the percentage as decimal (value \ total) and then when you want to render to a human you can make use of Habeeb's answer or using string interpolation you could have something even cleaner:

var displayPercentage = $"{(decimal)value / total:P}";

or

//Calculate percentage earlier in code
decimal percentage = (decimal)value / total;
...
//Now render percentage
var displayPercentage = $"{percentage:P}";

Solution 6 - C#

Bear in mind that you may need to cast one of the numbers to double if you have two ints

(double)i / events.Count * 100

Solution 7 - C#

In my case, I set two ints, and trying to calculate the percentage, and always get 0;

my code (before)

int Ff_Crm_Count = Ff_Crm.Count();
int Unfollowed_Ff_Crm_Count = Unfollowed_Ff_Crm.Count();
int The_Percentage = (Unfollowed_Ff_Crm_Count / Ff_Crm_Count) * 100);

after doing research (after)

double Ff_Crm_Count = Ff_Crm.Count();
double Unfollowed_Ff_Crm_Count = Unfollowed_Ff_Crm.Count();
double The_Percentage = Math.Round((double)((Unfollowed_Ff_Crm_Count / Ff_Crm_Count) * 100),2);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobinHoodView Question on Stackoverflow
Solution 1 - C#SoggerView Answer on Stackoverflow
Solution 2 - C#Nicolas RepiquetView Answer on Stackoverflow
Solution 3 - C#HabeebView Answer on Stackoverflow
Solution 4 - C#SonadorView Answer on Stackoverflow
Solution 5 - C#BronumskiView Answer on Stackoverflow
Solution 6 - C#Christian FindlayView Answer on Stackoverflow
Solution 7 - C#Nick ZhouView Answer on Stackoverflow