How to round a integer to the close hundred?

I don't know it my nomenclature is correct! Anyway, these are the integer I have, for example :

76
121
9660

And I'd like to round them to the close hundred, such as they must become :

100
100
9700

How can I do it faster in C#? I think about an algorithm, but maybe there are some utilities on C#?


Solution 1:

Try the Math.Round method. Here's how:

Math.Round(76d / 100d, 0) * 100;
Math.Round(121d / 100d, 0) * 100;
Math.Round(9660d / 100d, 0) * 100;

Solution 2:

I wrote a simple extension method to generalize this kind of rounding a while ago:

public static class MathExtensions
{
    public static int Round(this int i, int nearest)
    {
        if (nearest <= 0 || nearest % 10 != 0)
            throw new ArgumentOutOfRangeException("nearest", "Must round to a positive multiple of 10");

        return (i + 5 * nearest / 10) / nearest * nearest;
    }
}

It leverages integer division to find the closest rounding.

Example use:

int example = 152;
Console.WriteLine(example.Round(100)); // round to the nearest 100
Console.WriteLine(example.Round(10)); // round to the nearest 10

And in your example:

Console.WriteLine(76.Round(100)); // 100
Console.WriteLine(121.Round(100)); // 100
Console.WriteLine(9660.Round(100)); // 9700

Solution 3:

Try this expression:

(n + 50) / 100 * 100