2008-10-22 34 views
7

Potrzebuję zaokrąglić wartość do najbliższej wielokrotności 2,5.Zaokrąglasz do przyrostów 2,5?

Na przykład:
6 -> 7,5
7,6 -> 10
itp

Wydaje się, że najlepszym sposobem na to zrobić?

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 

Odpowiedz

19

Podziel liczbę przez 2,5, zaokrągla w górę do najbliższej liczby całkowitej, a następnie mnoży wynik przez 2,5.

Jesteś blisko.

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

Math.Ceiling zawsze będzie zaokrąglał liczbę całkowitą, więc nie potrzebujesz korekty po zakończeniu.

+1

Wygląda mi się jednak, że kod jest nie do regulacji wartości, które się zaokrągla się w dół przez pierwszą linię. Ale nie znam VB: przypuszczalnie istnieje Math.Ceil lub coś podobnego, które byłoby lepsze od Math.Round? –

+0

Zgoda ... Math.Ceiling może zostać zastąpiony przez Math.Round, aby osiągnąć ten sam efekt. – harpo

6

Podziel liczbę przez 2,5. Zaokrąglaj do najbliższej 1. Pomnóż przez 2,5.

Uważaj na błędy skumulowane i gotowe.

-Adam

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; 
Powiązane problemy