2009-10-07 173 views
48

我需要将一个double舍入到最接近的五个。我找不到使用Math.Round函数执行此操作的方法。我怎样才能做到这一点?四舍五入到最接近的五个

我想要什么:

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

等..

是否有一个简单的方法来做到这一点?

回答

96

尝试:

Math.Round(value/5.0) * 5; 
+4

此方法应该适用于任何数字:Math.Round(value/n)* n(请参阅:http://stackoverflow.com/questions/326476/vba-how-to-round-to-最接近5或10或者x) – 2009-10-07 13:55:44

+2

警告:由于浮点精度,这可能是“几乎四舍五入”...... – tbischel 2013-04-14 16:51:11

37

这工作:

5* (int)Math.Round(p/5.0) 
+3

+1因为int比decimal更好,在sebastiaan的例子中,需要将会导致类似你的例子。所以你的是完整的。 – 2009-10-07 13:54:10

+0

+1是的,这确实更好。 – user275587 2010-06-09 08:57:48

9

下面是一个简单的程序,让您验证码。 请注意MidpointRounding参数,如果没有它,您将舍入到最接近的偶数,在您的案例中意味着差值为5(在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(); 
     } 
    }