Percentage calculation

后端 未结 5 1772
死守一世寂寞
死守一世寂寞 2020-12-13 08:32

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 fr

相关标签:
5条回答
  • 2020-12-13 08:50

    Mathematically, to get percentage from two numbers:

    percentage = (yourNumber / totalNumber) * 100;
    

    And also, to calculate from a percentage :

    number = (percentage / 100) * totalNumber;
    
    0 讨论(0)
  • 2020-12-13 08:54

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

    0 讨论(0)
  • 2020-12-13 08:54

    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%

    0 讨论(0)
  • 2020-12-13 08:55

    Using Math.Round():

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

    or manually rounding:

    int percentComplete = (int)(0.5f + ((100f * complete) / total));
    
    0 讨论(0)
  • 2020-12-13 08:57

    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}";
    
    0 讨论(0)
提交回复
热议问题