/// <summary>
/// Rounds a number to the closest multiple of another number.
/// </summary>
/// <example>83 rounded to closest 25 would give a value of 75 (83 is closer to 75 than 100)</example>
/// <param name="num">The number to be rounded</param>
/// <param name="closest">The value you wish to round to the closest multiple of</param>
/// <returns>The rounded value</returns>
public int Round(int num, int closest) {
return (int)Math.Round(((double)num)/closest, 0) * closest;
}
Momerath
Nearly a Senior Poster
3,386 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
Be careful when using Math.Round, if you aren't familiar with how it works you may find some odd results. By default it uses MidPointRounding.ToEven which means that 4.5 would round to 4 not 5 as you might expect. Use the overloaded method to specify the MidPointRounding.AwayFromZero for the traditional rounding.
Ryshad
Nearly a Posting Virtuoso
1,307 posts since Aug 2009
Reputation Points: 512
Solved Threads: 246
what if the number im trying to round is a decimal.?
Not sure what you are asking. Math.Round accepts decimals if you want to round to a specific number of digits. If you are asking how do I round a decimal to the closest fraction of number, think powers of ten and use some basic math skills.
Momerath
Nearly a Senior Poster
3,386 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558