Python program to convert float decimal to Octal number
Last Updated :
14 Mar, 2023
Python doesn’t support any inbuilt function to easily convert floating point decimal numbers to octal representation. Let’s do this manually.
Approach : To convert a decimal number having fractional part into octal, first convert the integer part into octal form and then fractional part into octal form and finally combine the two results to get the final answer.
For Integer Part, 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.
For the Decimal Part, Keep multiplying the decimal part with 8 until and unless we get 0 left as fractional part. After multiplying the first time, note down an integral part and then again multiply the decimal part of new value by 8 and keep doing this until 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...)8
So, (7.16)10 = (7.1217...)8
or, (7.16)10 = (7.1217)8 (approx. value)
Below is the implementation :
def float_octal(number, places = 3 ):
whole, dec = str (number).split( "." )
whole = int (whole)
dec = int (dec)
res = oct (whole).lstrip( "0o" ) + "."
for x in range (places):
whole, dec = str ((decimal_converter(dec)) * 8 ).split( "." )
dec = int (dec)
res + = whole
return res
def decimal_converter(num):
while num > 1 :
num / = 10
return num
n = input ( "Enter your floating point value : \n" )
p = int ( input ( "Enter the number of decimal places of the result : \n" ))
print (float_octal(n, places = p))
|
Output :
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...