I'm looking for a method that can round a number up to the nearest multiple of another. This is similar Quantization.
Eg. If I want to round 81 up to the nearest multiple of 20, it should return 100.
Is there a method built-in method in the .NET framework I can use for this?
The reason I'm asking for a built-in method is because there's a good chance it's been optimized already.
public static int RoundUp(int num, int multiple)
{
if (multiple == 0)
return 0;
int add = multiple / Math.Abs(multiple);
return ((num + multiple - add) / multiple)*multiple;
}
static void Main()
{
Console.WriteLine(RoundUp(5, -2));
Console.WriteLine(RoundUp(5, 2));
}
/* Output
* 4
* 6
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With