Private Sub Command1_Click()
Dim aa1 As Double
Dim aa2 As Double
Dim bb As Double
Dim aa As Double
aa1 = 1.36
aa2 = 0.04
aa = aa1 + aa2
bb = 1.4
Debug.Print ("bb= " & Num2Bin(bb))
Debug.Print ("aa1=" & Num2Bin(aa1))
Debug.Print ("aa2=" & Num2Bin(aa2))
Debug.Print ("aa= " & Num2Bin(aa))
Debug.Print ("1.4=" & Num2Bin(1.4))
If aa > bb Then
MsgBox aa & ">" & bb
ElseIf aa = bb Then
MsgBox aa & "=" & bb
Else
MsgBox aa & "<" & bb
End If
End Sub
Public Function Num2Bin(ByVal q As Variant, _
Optional ByVal Precision As Integer = 13) As String
'Declarations
Dim ln2 As Double 'Cache the value of Log(2)
Dim sResult As String 'Temp variable to hold the result
Dim fStart As Boolean 'Flag to indicate if we have started the number
Dim i As Long
Dim l As Long
Dim qL As Long, qD As Double
'Implementation
If IsNumeric(q) Then
'Cache this value, it's very useful!
ln2 = Log(2)
'Don't use Int(...), as this limits the range to integers
i = Log(q) / ln2
If i > 30 Then
'Overflow
Err.Raise 6, "Num2Bin", "Overflow"
Else
'Bitwise operators use CLng on the operands
'e.g. 0.75 And 1 = 1
'To get around this, use a Long copy of q
'and check for rounding up
qL = CLng(q)
If qL > q Then qL = qL - 1
Do While i >= 0
l = Exp(i * ln2)
If (qL And l) Then
sResult = sResult & "1"
qL = qL - l
q = q - l
'Have started the number
fStart = True
ElseIf fStart Then
'Do not write leading zeros
'This is needed because CLng(Log(q) / Log(2))
'may round up.
sResult = sResult & "0"
End If
i = i - 1
Loop
'If we haven't got a value yet, the integer part is 0
If sResult = vbNullString Then sResult = "0"
If q > 0 And Precision > 0 Then
'Need to deal with fractional part
sResult = sResult & "."
i = -1
'Convert q to a double
qD = CDbl(q)
'Stop when q=0 or have reached max precision
Do While qD > 0 And Precision > 0
qD = qD * 2
If Int(qD) = 1 Then
sResult = sResult & "1"
qD = qD - 1
Else
sResult = sResult & "0"
End If
i = i - 1
Precision = Precision - 1
Loop
End If
Num2Bin = sResult
End If
Else
'q is not numeric
Err.Raise 13, "Num2Bin", "Type Mismatch"
End If
End Function