Octal conversion to decimal

171 Views Asked by At

How to convert octal to decimal? My code works for integers, such as 25 and 60. But if I let the octal number to be non-integer, the return value truncates the digits after the decimal point. How could I edit this one?

import math


def octalToDecimal(octalNumber):
    decimalNumber=0
    i = 0
    while (math.floor(octalNumber) != 0):
        rem = math.floor(octalNumber) % 10
        octalNumber /= 10
        decimalNumber += rem * 8**i
        i+=1
        
   
    return decimalNumber

q=25.63

p=octalToDecimal(q) 
print("The decimal representatation of {} is {}.".format(q, p))
1

There are 1 best solutions below

0
On

The final code would look something like

def octalToDecimal(octal):
    integ, frac = octal.split('.')

    decimal = 0
    for i, n in enumerate(reversed(integ)):
        decimal += int(n) * 8**(i)
    for i, n in enumerate(frac):
        decimal += int(n) / 8**(i+1)

    return decimal


q = '25.63'
p = octalToDecimal(q)
print(f'The decimal representatation of {q} is {p}.')

resulting in $21.796875$. If you disagree with the string representation you could always use str() inside the octalToDecimal function.