2009-10-07 83 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(); 
     } 
    }