The Round function in vb.net is not always like u want it. Not in my case.
I wanted to round every up. For example 1.5 to 2 and 2.5 to 3.
When i used the Round function in vb.net it uses bankers rounding. This means that is rounds to the nearest integer.
So, if there are two nearest integers then it goes to the even one. For example 1.5 rounds to 2 and 0.5 rounds to 0.
This is done because if u round millions of value’s it will give an average.
I’ve been searching for a while to find a good solution for this case. I thought i found one on an other forum wich worked on first sight
but while actually using it i saw that somethimes a 4 rounds to 5.
So i finally decided to write my own function
It is used to round only to 2 decimals but it is easaly adjustable.
Function MyRoundFunction(ByVal dblValue As Double) As Double
Dim strValue As String = dblValue.ToString
Dim strAfterKomma, strBeforeComma, strAll() As String
strAll = strValue.Split(”,”)
strBeforeComma = strAll(0)
strAfterKomma = strAll(1)Dim strResult As String
Dim blnPlus As Boolean = False
Dim i As IntegerDim intLengte_Totaal = strAfterKomma.Length
For i = intLengte_Totaal To 1 Step -1
Dim intValueBetween = CType(Mid(strAfterKomma, i, 1), Integer)
If blnPlus = True Then
intValueBetween += 1
blnPlus = False
End If
If i >= 3 Then
If intValueBetween > 4 Then
If intValueBetween = 10 Then
intValueBetween = 0
End IfblnPlus = True
End If
Else
blnPlus = False
If intValueBetween = 10 Then
intValueBetween = 0
blnPlus = True
End IfEnd If
strResult = CType(intValueBetween, String) & strResult
Next
If blnPlus = True Then
strBeforeComma = CType(CType(strBeforeComma, Integer) + 1, String)
End If
Return CType(strBeforeComma & “,” & Microsoft.VisualBasic.Left(strResult, 2), Double)
End Function
| M | T | W | T | F | S | S |
|---|---|---|---|---|---|---|
| « Nov | ||||||
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
| 29 | 30 | 31 | ||||
One Response
Joe
April 14th, 2009 at 4:27 pm
1That seems overly complicated. VB.NET lets you can change the rounding method to use common rounding instead of Bankers.
Math.Round(2.5, 0, MidpointRounding.AwayFromZero))
RSS feed for comments on this post · TrackBack URI
Leave a reply