# Python program to convert floating to binary

PythonProgrammingServer Side Programming

Given a floating point value and input the decimal places number, our task is to convert it to binary form.

First we take the integer part from the floating point value and convert it to binary then take fractional part and convert it to binary form and lastly combining both.

## Example

The floating point value is 22.625
Convert decimal 22 to binary 10110. Convert decimal 0.625 to binary 0.101. Combine integer and fraction to obtain binary 10110.101.


## Example Code

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


## Output

Enter floating point value :
2.34
Enter the number of decimal places of the result :
3
10.256

Published on 22-Nov-2018 05:36:39