2008-10-22 16 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 

गणित। छत हमेशा गैर-पूर्णांक को घेरेगी, इसलिए आपको पोस्ट-एडजस्टमेंट की आवश्यकता नहीं है।

+1

मानो कि कोड है मूल्यों है कि पहली लाइन द्वारा पूर्णांक हो समायोजित करने के लिए मेरे लिए लग रहा है। लेकिन मुझे वीबी नहीं पता: संभवतः एक गणित है। सील या इसी तरह जो गणित से बेहतर होगा। राउंड? –

+0

सहमत ... गणित। मृदा के लिए छत को प्रतिस्थापित किया जा सकता है। इसी प्रभाव को प्राप्त करने के लिए राउंड। – harpo

6

संख्या 2.5 से विभाजित करें। निकटतम दौर 1. 2.5 से गुणा करें।

संचयी त्रुटियों से सावधान रहें, और आप सभी सेट हैं।

-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; 
संबंधित मुद्दे