Two Hoots Banner



Visual Basic Maths Tips

  • The following function converts a decimal number (base 10) to another base number system, upto Base 36. Pass the number to be converted as a double and an optional byte value representing the base to convert to.
Public Function ConvertDecToBaseN(ByVal dValue As Double, _
          Optional ByVal bybase As Byte = 16) As String

Const BASENUMBERS As String = "01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"

Dim sResult As String
Dim dRemainder As Double

On Error GoTo errorhandler

sResult = ""
If (bybase > 2) And (bybase < 37) Then
  dValue = Abs(dValue)
  Do
    dRemainder = dValue - (bybase * Int((dValue / bybase)))
    sResult = Mid$(BASENUMBERS, dRemainder + 1, 1) & sResult
    dValue = Int(dValue / bybase)
  Loop While (dValue > 0)
End If
ConvertDecToBaseN = sResult
Exit Function

errorhandler:

  Err.Raise Err.Number, "ConvertDecTobaseN", Err.Description
    
End Function