Python program to convert floating to binary
Last Updated :
15 Jun, 2022
Python doesn’t provide any inbuilt method to easily convert floating point decimal numbers to binary number. So, Let’s do this manually. Approach : To convert a floating point decimal number into binary, first convert the integer part into binary form and then fractional part into binary form and finally combine both results to get the final answer. For Integer Part, keep dividing the number by 2 and noting down the remainder until and unless the dividend is less than 2. If so, stop and copy all the remainders together. For Decimal Part, keep multiplying the decimal part with 2 until and unless 0 left as fractional part. After multiplying the first time, note down integral part and again multiply decimal part of the new value by 2. Keep doing this until reached a perfect number.
Above steps can be written as : 1(base 10) = 1(base 2) and .234(base 10) = .0011(base 2) Now, to get the binary of 1.234, merge both results as a complete number. (1)10 = (1)2 (.234)10 = (.0011)2 (1.234)10 = (1.0011…)2 (1.234)10 = (1.0011)2 [approx.]
Below is the implementation :
Python3
def float_bin(number, places = 3 ):
whole, dec = str (number).split( "." )
whole = int (whole)
dec = int (dec)
res = bin (whole).lstrip( "0b" ) + "."
for x in range (places):
whole, dec = str ((decimal_converter(dec)) * 2 ).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_bin(n, places = p))
|
Output :
Enter your floating point value :
1.234
Enter the number of decimal places of the result :
4
1.0011
Enter your floating point value :
11.234
Enter the number of decimal places of the result :
4
1011.0011
Time Complexity : O(logn)
Auxiliary Space: O(1) if we use stack or arrays then O(logn) space will required
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...