Skip to content

Commit 849b4f4

Browse files
committed
feat(numeric-helper): add utility methods
1 parent b5fa5a8 commit 849b4f4

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

SharpHelpers/SharpHelpers/NumericHelper.cs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,5 +128,64 @@ public static int Abs(this int number)
128128
{
129129
return Math.Abs(number);
130130
}
131+
132+
/// <summary>
133+
/// Checks if the integer is divisible by a specified divisor.
134+
/// </summary>
135+
/// <param name="number">The number to check.</param>
136+
/// <param name="divisor">The divisor.</param>
137+
/// <returns>True if divisible; otherwise, false.</returns>
138+
public static bool IsDivisibleBy(this int number, int divisor)
139+
{
140+
if (divisor == 0) throw new DivideByZeroException("Divisor cannot be zero.");
141+
return number % divisor == 0;
142+
}
143+
144+
/// <summary>
145+
/// Calculates the percentage this number represents of a total.
146+
/// </summary>
147+
/// <param name="number">The partial value.</param>
148+
/// <param name="total">The total value.</param>
149+
/// <returns>The percentage as a double.</returns>
150+
public static double ToPercentageOf(this int number, int total)
151+
{
152+
if (total == 0) throw new DivideByZeroException("Total cannot be zero.");
153+
return (double)number / total * 100;
154+
}
155+
156+
/// <summary>
157+
/// Checks whether the integer is within the specified inclusive range.
158+
/// </summary>
159+
/// <param name="number">The number to check.</param>
160+
/// <param name="min">The minimum bound.</param>
161+
/// <param name="max">The maximum bound.</param>
162+
/// <returns>True if within range; otherwise, false.</returns>
163+
public static bool IsInRange(this int number, int min, int max)
164+
{
165+
return number >= min && number <= max;
166+
}
167+
168+
/// <summary>
169+
/// Returns the next multiple of the specified factor greater than or equal to the number.
170+
/// </summary>
171+
/// <param name="number">The base number.</param>
172+
/// <param name="factor">The factor.</param>
173+
/// <returns>The next multiple of the factor.</returns>
174+
public static int NextMultipleOf(this int number, int factor)
175+
{
176+
if (factor == 0) throw new ArgumentException("Factor cannot be zero.");
177+
int remainder = number % factor;
178+
return remainder == 0 ? number : number + (factor - remainder);
179+
}
180+
181+
/// <summary>
182+
/// Checks whether the integer is a power of two.
183+
/// </summary>
184+
/// <param name="number">The number to check.</param>
185+
/// <returns>True if the number is a power of two; otherwise, false.</returns>
186+
public static bool IsPowerOfTwo(this int number)
187+
{
188+
return number > 0 && (number & (number - 1)) == 0;
189+
}
131190
}
132191
}

0 commit comments

Comments
 (0)