2013-08-20 95 views
0

我试图创建一个函数,将数字四舍五入为给定数字的整数的最接近倍数。四舍五入到数字的多个

因此,如果号码是15,我们有

  • 14,4轮15个
  • -14,4回合-15
  • 14,5轮15个
  • 28回合30分
  • -28两轮至-30

等。我已经有一些代码,但似乎没有按预期的那样工作:

public static int RoundToFactor(float number, float Factor) 
{ 
     int returnNumber; 

     if((number%Factor) == 0) { 
      returnNumber = (int)number; 
     } 

     returnNumber = (int) (Mathf.Round(number/Factor)*Factor); 

     return returnNumber; 
} 
+1

哪种语言? –

+0

c#但任何languague是好的 –

+0

可能的重复:http://stackoverflow.com/questions/274439/built-in-net-algorithm-to-round-value-to-the-nearest-10-interval – tmh

回答

0

这是我制作的一种方法。它应该适合您的需求。我添加了一个额外的参数,要求在同样接近时向上舍入或向下舍入。 (同样,如果你注意到数字看起来有错误,当它们为负数时,例如199取整为2的舍入因子,如有必要,则为200.将199改为-199,结果变成-198,这不是这是一个简单的四舍五入的错误。)

public static double RoundToFactor(double Number, int Factor, bool RoundDirection = true) 
    {/*round direction: in the event that the distance is 
     * equal from both next factors round up (true) down (false)*/ 

     double multiplyBy; 
     if ((Number % Factor).Equals(0f)) 
     { 
      return Number; 
     } 
     else 
     { 
      multiplyBy = Math.Round(Number/Factor); 
      int Low = (int)multiplyBy - 1; 
      int Mid = (int)multiplyBy; 
      int High = (int)multiplyBy + 1; 

      List<double> li = new List<double>() { Low, Mid, High }; 
      double minDelta = double.MaxValue; 
      double Closest = 0d; 

      foreach (double dbl in li) 
      { 
       double db = dbl * Factor; 
       double Delta = (db < Number) ? (Number - db) : (db - Number); 
       if (RoundDirection ? Delta <= minDelta : Delta < minDelta) 
       { 
        minDelta = Delta; 
        Closest = db; 
       } 
      } 
      return Closest; 

     } 

     throw new Exception("Math has broken!!!"); 
    }