VB 6.0 - rounding

Asked By john shenouda on 27-Jan-12 07:55 PM
how i can use the round with vb6 same as roundin with excel

exam : i need rounding  from 0.00525 to 0.0053



the defult round is 0.0052 this is err 
Danasegarane Arunachalam replied to john shenouda on 27-Jan-12 08:54 PM
Handle the second parameter in the Round Function

Round(m,n) where the M is the number and the n is the number of decimal position. If it is 3 then it will be rounded to 3 decimal places


Round(0.00525,4) outputs - > 0.0053


Donald Ross replied to Danasegarane Arunachalam on 27-Jan-12 09:08 PM


Don
[)ia6l0 iii replied to john shenouda on 27-Jan-12 09:17 PM
Yes, as you say, the default Round function would not work for values like 0.05...that is because it used the underlying operating system values for the numbers which are in nature less than 0.05. So the Round function does not work in this case.

Another interesting thing to note is that VB6 implements Banker's rounding, where as the Excel implements Symmetric  Arithematic Rounding. So you have to write custom routines in VB6 to achieve the same result as the Excel equivalent. 
http://support.microsoft.com/kb/196652/EN-US is a Microsoft Support article that talks about this problem in more detail.  

And here is a custom routine from my codebase, that I have used some time back. I am not sure who originally wrote it. But whoever did, figured out the problem with Round function quite earlier than us. 

Function BRound(ByVal X As Double, Optional ByVal Factor As Double = 1) As Double
'  For small number:
'  BRound = CLng(X * Factor) / Factor

Dim Temp As Double, FixTemp As Double
  Temp = X * Factor
  FixTemp = Fix(Temp + 0.5 * Sgn(X))
  ' If the value is .5
  If Temp - Int(Temp) = 0.5 Then
    If FixTemp / 2 <> Int(FixTemp / 2) Then ' check if odd
      ' Reduce  by 1 to make even
      FixTemp = FixTemp - Sgn(X)
    End If
  End If
  BRound = FixTemp / Factor
End Function


Hope this helps.
Venkat K replied to john shenouda on 28-Jan-12 12:19 AM
Pass the number of digits that you need to round and the value to the below function to get the result:

Private Function RoundOff(ByVal value As Double, ByVal _ digits As Integer) As Double
Dim shift As Double
shift = 10 ^ digits
RoundOff = CInt(value * shift) / shift
End Function

How to call:

RoundOff(0.00525,4)

Thanks