Fractional to decimal conversion in VBA

Asked

Viewed 20 times

-2

Good morning, I need to run a program that converts a fractional decimal to binary. If I don’t have an exact representation, I must enter a number of significant digits. However, I’m not able to perform. My code:

Sub Binario_P_Decimal2()

    Dim Numero As Single, Binario As String, fra As Single, BinarioFra As String, resto As Single
    Numero = InputBox("Informe o seu número ")
    fra = Numero - Int(Numero)
    NDS = 9
    Do While Numero > 0
        If (Numero Mod 2) = 0 Then
            Binario = Binario & "0"
        Else
            Binario = Binario & "1"
        End If
        Numero = Numero \ 2
    Loop
    Do While fra <> 0# And i < NDS
        If Int(fra) >= 1 Then
            BinarioFra = BinarioFra & "1"
        Else
            BinarioFra = BinarioFra & "0"
        End If
        fra = fra * 2 + fra
        i = i + 1
    Loop
    MsgBox (" O seu número binário é " & StrReverse(Binario) & BinarioFra)
End Sub

1 answer

0

Good morning Excel has a Worksheet.Function called Dec2bin. Already tried?

You can also try (codegrapper.com):

    Function DecToBin$(ByVal n&)
      Do
         DecToBin = n Mod 2 & DecToBin
         n = n \ 2
      Loop While n
    End Function

Example: Msgbox Dectobin(9512489) '<-result: 100100010011000101001

Browser other questions tagged

You are not signed in. Login or sign up in order to post.