Wednesday, November 7, 2018

Decimal to Binary conversion of a number with fractional part - Python3

def dec_to_bin(dec):
    dec = dec.split('.')
    num = int(dec[0])
    frac = 0
    try:
        frac = float("." + dec[1])
    except IndexError:
        pass

    bin = []

    while num > 0:
        rem = num % 2
        bin.append(str(rem))
        num = num // 2

    bin_dec = []
    counter = 0
    if (frac == 0):
        bin_dec.append('0')
    while frac != 0:
        n = frac * 2
        d = int(n)
        n -= d
        bin_dec.append(str(d))
        frac = n
    print("Binary : ","".join(bin[::-1] + ['.'] + bin_dec))
    
dec = str(float(input("Enter a decimal number: ")))
dec_to_bin(dec)


Screen Shot



No comments:

Post a Comment