C# Calculate Percentage

Simple percentage calculation as an injectable service.

Yeah I got tired of Google’ling which number number you divide by each time I needed to do this in code :)

Simply put this is: (100 * scoreAchieved) / outOf which is generally (100 * small number) / big number.

Interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
namespace Foo.Common.Maths.Interfaces
{
public interface IPercentageCalculator
{
/// <summary>
/// Calculate the score achieved as a percentage out of the given value `outOf`
/// </summary>
/// <param name="scoreAchieved">Example: 73</param>
/// <param name="outOf">Example: 100</param>
/// <returns>73.00 as the default decimal spacing is .00 (2 digits)</returns>
double GetPercentage(int scoreAchieved, int outOf);

/// <summary>
/// Calculate the score achieved as a percentage out of the given value `outOf`
/// </summary>
/// <param name="scoreAchieved">Example: 73</param>
/// <param name="outOf">Example: 100</param>
/// <param name="digits">Example: 3</param>
/// <returns>73.000</returns>
double GetPercentage(int scoreAchieved, int outOf, int digits);
}
}

Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;

namespace Foo.Common.Maths
{
///<inheritdoc/>
public class PercentageCalculator : IPercentageCalculator
{
private const int DIGITS = 2;

public double GetPercentage(int scoreAchieved, int outOf)
{
if (scoreAchieved == 0 || outOf == 0)
return 0;

return GetPercentage(scoreAchieved, outOf, DIGITS);
}

public double GetPercentage(int scoreAchieved, int outOf, int digits)
{
if (scoreAchieved == 0 || outOf == 0)
return 0;

return Math.Round((double)(100 * scoreAchieved) / outOf, digits);
}
}
}

References