0

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
    Welcome to MSE. Your question seems to be more appropriate for StackOverflow, and I would suggest you ask your question there instead. – Martin Westin Mar 14 '23 at 15:31
  • After the second round of the loop, your octalNumber has become 0.2563 which has floor zero and the loop terminates. So your loop never addresses the fractional part of 25.63. – Semiclassical Mar 14 '23 at 15:38
  • You would probably want to make $q$ a string (due to floating point precision) and split the string at ".", your program can handle the integer part and the fractional part of 63 in your example would result in $6/8 + 3/8^2$ in decimal. – jorisperrenet Mar 14 '23 at 15:39

1 Answers1

0

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.