Wednesday, November 7, 2018

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

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

    hex = []

    while num > 0:
        rem = num % 16
        hex.append(str(rem))
        num = num // 16

    hex_dec = []
    counter = 0
    if (frac == 0):
        hex_dec.append('0')
    while frac != 0:
        n = frac * 16
        d = int(n)
        n -= d
        hex_dec.append(str(d))
        frac = n
    print("Hexadecimal : ","".join(hex[::-1] + ['.'] + hex_dec))
    
dec = str(float(input("Enter a decimal number: ")))
dec_to_hex(dec)


Screenshot

No comments:

Post a Comment