Computer >> Computer tutorials >  >> Programming >> Python

Python program to convert float decimal to octal number


Given a float decimal value and input the decimal places number, our task is to convert it to octal form.

At first, we take the integer part from the floating point value and convert it to octal then we take fractional part and convert it to octal form and lastly combine both.

So, first step is to take Integer Part and keep dividing the number by 8 and noting down the remainder until and unless the dividend is less than 8 and copy all the remainders together.

Second step is the Decimal Part and keep multiplying the decimal part with 8 until and unless we get 0 left as fractional part and after multiplying the first time noting down an integral part and then again multiplying the decimal part of new value by 8 and keep doing this until perfect number is reached.

Example code

def float_convert_octal(my_number, places = 3):
   my_whole, my_dec = str(my_number).split(".")
   my_whole = int(my_whole)
   my_dec = int (my_dec)
   res = oct(my_whole).lstrip("0o") + "."
   for x in range(places):
      my_whole, my_dec = str((decimal_converter(my_dec)) * 8).split(".")
      my_dec = int(my_dec)
      res += my_whole
   return res
def decimal_converter(num):
   while num > 1:
      num /= 10
   return num
n = input("Enter the floating point value : \n")
p = int(input("Enter the number of decimal places of the result : \n"))
print(float_convert_octal(n, places = p))

Output

Enter the floating point value :
 6.89
Enter the number of decimal places of the result :
 12
6.707534121727