views:

629

answers:

3

Hi!

I'm using C# and 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?

+14  A: 

Try

Math.Round(value / 5.0) * 5;

Hope this helps!

Regards,

Sebastiaan

Sebastiaan Megens
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
+4  A: 

This works:

5* (int)Math.Round(p / 5.0)
Mike Polen
+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
+1 yep it is indeed better.
+1  A: 

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();
        }
    }
Yacoder