5
\$\begingroup\$

This accepts values from a user that needs to show up in a intervals of some number. In this case, we will say intervals of 5.

Is there a better way to do this?

public static int RoundTo(this int value, int roundTo)
{
    var midPoint = roundTo / 2.0;
    var remainder = value % roundTo;
    var result = remainder < midPoint 
        ? (value - remainder) //round down
        : (value + (roundTo - remainder)); //round up
    return result;
}

Example

Console.WriteLine(7.RoundTo(5)); //5
Console.WriteLine(8.RoundTo(5)); //10
\$\endgroup\$
6
\$\begingroup\$

You could use the build-in Math.Round method:

public static int RoundTo(this int value, int roundTo)
{
    return (int)Math.Round((double)value / roundTo) * roundTo;
}

Using this approach you can round not only ints:

public static double RoundTo(this double value, double roundTo)
{
    return Math.Round(value / roundTo) * roundTo;
}

As for your approach, you don't need midPoint:

public static int RoundTo(this int value, int roundTo)
{
    var remainder = value % roundTo;
    var result = remainder < roundTo - remainder
        ? (value - remainder) //round down
        : (value + (roundTo - remainder)); //round up
    return result;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.