Wednesday, November 7, 2018

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

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

    while num > 0:
        rem = num % 8
        oct.append(str(rem))
        num = num // 8

    oct_dec = []
    counter = 0
    if(frac==0):
        oct_dec.append('0')
    while frac != 0:
        n = frac * 8
        d = int(n)
        n -= d
        oct_dec.append(str(d))
        frac = n

    print("Octal : ","".join(oct[::-1]+['.']+oct_dec))

dec = str(float(input("Enter a decimal number: ")))
dec_to_oct(dec)


Screenshot

No comments:

Post a Comment