Round to nearest five

Viewed 58751

I need to round a double to nearest five. I can't find a way to do it with the Math.Round function. How can I do this?

What I want:

70 = 70
73.5 = 75
72 = 70
75.9 = 75
69 = 70

and so on..

Is there an easy way to do this?

5 Answers

You can also write a generic function:

Option 1 - Method

public int Round(double i, int v)
{
    return (int)(Math.Round(i / v) * v);
}

And use it like:

var value = Round(72, 5);

Option 2 - Extension method

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

And use it like:

var price = 72.0;
var newPrice = price.Round(5);

I did this this way:

int test = 5 * (value / 5); 

for the next value (step 5) above, just add 5.

Related