舍入到最接近的五

Mar*_*tin 67 c# double rounding

我需要将一个双舍入到最接近的五.我找不到使用Math.Round函数的方法.我怎样才能做到这一点?

我想要的是:

70 = 70
73.5 = 75
72 = 70
75.9 = 75
69 = 70
Run Code Online (Sandbox Code Playgroud)

等等..

是否有捷径可寻?

Seb*_*n M 118

尝试:

Math.Round(value / 5.0) * 5;
Run Code Online (Sandbox Code Playgroud)

  • 这个方法适用于任何数字:Math.Round(value/n)*n(见这里:http://stackoverflow.com/questions/326476/vba-how-to-round-to-nearest-5-or- 10或-x)的 (4认同)
  • 警告:由于浮点精度,这可能会"几乎圆润"...... (2认同)

Mik*_*len 46

这有效:

5* (int)Math.Round(p / 5.0)
Run Code Online (Sandbox Code Playgroud)

  • +1因为int优于十进制,而在sebastiaan的例子中,需要强制转换,这会产生类似于你的例子.所以你的是完整的. (5认同)

Max*_*kin 13

这是一个简单的程序,允许您验证代码.请注意MidpointRounding参数,如果没有它,您将四舍五入到最接近的偶数,在您的情况下,这意味着相差五(在72.5示例中).

    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();
        }
    }
Run Code Online (Sandbox Code Playgroud)