+

Python program to convert decimal floating point number to octal number

Approach. To convert a decimal number that has a fractional part to octal, first convert the integer part to octal, then the fractional part to octal, and finally combine the two results to get the final answer. 
For the integer part, keep dividing the number by 8 and noting the remainder until the dividend is less than 8, and copy all the rest together. 
For the decimal part, keep multiplying the decimal part by 8 until we get 0 as a fractional part. After multiplying for the first time, write down the integral part, then multiply the decimal part of the new value by 8 again and keep doing this until the perfect number is reached.

Above steps can be written as:
7 (base 10) = 7 (base 8) and .16 (base 10) = .1217 (base 8)

Now , to get the octal of the decimal number 7.16, merge the two octal results.
(7) 10 = (7) 8

 (0.16) 10 = (0.1217 & # 8230;) 8
So, (7.16) 10 = (7.1217 & # 8230;) 8
or, (7.16) 10 = (7.1217) 8 (approx. value)

Below is the implementation:

# Python3 demo program
# octal type conversion

 
# The function returns octal representation
# of the value passed as parameters. & # 39; number & # 39;
# - decimal floating point number and "places"
# number of decimal places

def float_octal (number, places = 3 ):

 

  # split () separates integer and decimal

# part and saves it in two separate variables

  whole, dec = str (number) .split ( "." )

 

# Convert both integer and decimal

# part from string type to integer type

whole = int (whole)

dec = int (dec)

 

# Convert the integer part of the number to

# the corresponding octal form and remove

# & quot; 0о & quot; from this.

res = oct (whole) .lstrip ( "0o" ) + "."

 

# Iterate how many times we want

# number of decimal places

for x in range (places):

  

# Multiply the decimal value by 8 and separate

  # integer part and decimal part

  whole, dec = str ((decimal_converter (dec )) * 8 ). split ( "." )

 

# Convert decimal

# integer again

dec = int (dec)

 

# continue adding Insert integer parts

# received into result variable

res + = whole

 

return res

  
# The function converts the value passed as
# parameter to the corresponding decimal
# view

def decimal_converter (num):

while num & gt;  1 :

num / = 10

return num

 
Driver code

 
# Take user input for
# floating point number

n = input ( " Enter your floating point value: " )

 
# Take user input for decimal number
# places the user would like to get the result as

p = int ( input ( "Enter the number of decimal places of the result:" ))

 

print (float_octal (n, places = p))

Exit:

 Enter your floating point value: 7.16 Enter the number of decimal places of the result: 10  7.1217273146  
 Enter your floating point value: 7.1234 Enter the number of decimal places of the result: 5  7.07713  
Get Solution for free from DataCamp guru