Round to nearest five

后端 未结 4 1495
忘了有多久
忘了有多久 2020-12-02 21:54

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 = 7         


        
相关标签:
4条回答
  • 2020-12-02 22:21

    This works:

    5* (int)Math.Round(p / 5.0)
    
    0 讨论(0)
  • 2020-12-02 22:21

    I did this this way:

    int test = 5 * (value / 5); 
    

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

    0 讨论(0)
  • 2020-12-02 22:32

    Try:

    Math.Round(value / 5.0) * 5;
    
    0 讨论(0)
  • 2020-12-02 22:40

    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();
            }
        }
    
    0 讨论(0)
提交回复
热议问题