2008-10-22 33 views
7

我需要將值舍入到2.5的最接近倍數。以2.5遞增?

例如:
6 - > 7.5
7.6 - > 10

這似乎是做到這一點的最好方法是什麼?

Function RoundToIncrement(ByVal originalNumber As Decimal, ByVal increment As Decimal) As Decimal 

     Dim num = Math.Round(originalNumber/increment, MidpointRounding.AwayFromZero) * increment 
     If originalNumber Mod increment <> 0 And num < originalNumber Then 
      num += increment 
     End If 
     Return num 

    End Function 

回答

19

將數字除以2.5,湊整到最接近的整數,然後將結果乘以2.5。

你很近。

Function RoundToIncrement(ByVal orignialNumber As Decimal, ByVal increment As Decimal) As Decimal 
    Return Math.Ceiling(orignialNumber/increment) * increment 
End Function 

Math.Ceiling將始終舍入非整數,因此不需要進行後期調整。

+1

看起來對我來說,就好像這些代碼是存在的調整是那些獲得由第一線向下取整數值。但我不知道VB:大概是Math.Ceil或類似的,比Math.Round更好嗎? – 2008-10-22 20:41:02

6

將數字除以2.5。舍入到最接近的1.乘以2.5。

請注意累積錯誤,並且您已完成設置。

- 亞當

2
 /* 
       This will round up (Math.Ceiling) or down (Math.Floor) based on the midpoint of the increment. 
       The other examples use Math.Ceiling and therefore always round up. 
       Assume the increment is 2.5 in this example and the number is 6.13 
      */ 
      var halfOfIncrement = Increment/2;         // 2.5/2 = 1.25 
      var floorResult = Math.Floor(originalNumber/Increment);    //Math.Floor(6.13/2.5) = Math.Floor(2.452) = 2 
      var roundingThreshold = (floorResult * Increment) + halfOfIncrement; //(2 * 2.5) = 5 + 1.25 = 6.25 

      if (originalNumber >= roundingThreshold)        //6.13 >= 6.25 == false therefore take Math.Floor(6.13/2.5) = Math.Floor(2.452) = 2 * 2.5 = 5 
       result = Math.Ceiling(originalNumber/Increment) * Increment; 
      else 
       result = Math.Floor(originalNumber/Increment) * Increment;