舍入到2.5的增量?

时间:2008-10-22 20:16:50

标签: vb.net

我需要将值舍入到最接近的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

3 个答案:

答案 0 :(得分: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 :(得分:6)

将数字除以2.5。舍入到最接近1.乘以2.5。

小心累积错误,并且你已经完成了设置。

- 亚当

答案 2 :(得分: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;