2008-10-22 19 views
7

Necesito redondear un valor hasta el múltiplo más cercano de 2.5.Redondea a incrementos de 2.5?

Por ejemplo:
6 -> 7,5
7.6 -> 10
etc.

Esta parece ser la mejor manera de hacer esto?

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 

Respuesta

19

Divide el número por 2,5, redondear al entero más próximo, a continuación, multiplicar el resultado por 2,5.

Estás cerca.

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

Math.Ceiling siempre redondeará no enteros arriba, por lo que no necesita el ajuste posterior.

+1

A mi me parece como si ese código está ahí para ajustar los valores que consiguen redondeado hacia abajo en la primera línea. Pero no sé VB: presumiblemente hay un Math.Ceil o similar que sería mejor aquí que Math.Round? –

+0

De acuerdo ... Math.Ceiling podría ser sustituido por Math.Round para lograr el mismo efecto. – harpo

6

Divida el número por 2.5. Redondea al más cercano 1. Multiplica por 2.5.

Tenga cuidado con los errores acumulativos, y ya está todo listo.

-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;