HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Round to specified int

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
specifiedintround

Problem

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

Solution

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;
}

Code Snippets

public static int RoundTo(this int value, int roundTo)
{
    return (int)Math.Round((double)value / roundTo) * roundTo;
}
public static double RoundTo(this double value, double roundTo)
{
    return Math.Round(value / roundTo) * roundTo;
}
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;
}

Context

StackExchange Code Review Q#109319, answer score: 8

Revisions (0)

No revisions yet.