85

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?

Rob
  • 26,989
  • 16
  • 82
  • 98
Martin
  • 2,269
  • 3
  • 19
  • 10

5 Answers5

153

Try:

Math.Round(value / 5.0) * 5;
Sebastiaan M
  • 5,775
  • 2
  • 27
  • 28
  • 4
    This method should work for any number: Math.Round( value / n ) * n (see here: http://stackoverflow.com/questions/326476/vba-how-to-round-to-nearest-5-or-10-or-x) – TK. Oct 07 '09 at 13:55
  • 2
    warning: this would likely be "almost rounded", due to floating point precision... – tbischel Apr 14 '13 at 16:51
58

This works and removes the need for an outer cast:

5 * (int)Math.Round(n / 5.0)
Aurumaker72
  • 33
  • 1
  • 7
Mike Polen
  • 3,586
  • 1
  • 27
  • 31
  • 5
    +1 because int is better than decimal and in sebastiaan's example one need to cast which would result in something like your example. so yours is the complete one. – J. Random Coder Oct 07 '09 at 13:54
15

Here is a simple program that allows you to verify the code. Be aware of the MidpointRounding parameter, without it you will get rounding to the closest even number, which in your case means difference of five (in the 72.5 example).

    class Program
    {
        public static void RoundToFive()
        {
            Console.WriteLine(R(71));
            Console.WriteLine(R(72.5));  //70 or 75?  depends on midpoint rounding
            Console.WriteLine(R(73.5));
            Console.WriteLine(R(75));
        }

        public static double R(double x)
        {
            return Math.Round(x/5, MidpointRounding.AwayFromZero)*5;
        }

        static void Main(string[] args)
        {
            RoundToFive();
        }
    }
Massimiliano
  • 16,770
  • 10
  • 69
  • 112
4

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);
Jeff
  • 4,285
  • 15
  • 63
  • 115
Jonne Kleijer
  • 592
  • 5
  • 14
2

I did this this way:

int test = 5 * (value / 5); 

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

Elletlar
  • 3,136
  • 7
  • 32
  • 38