Python program to convert floating to binary

In this article, we will see how to convert floating-point value to binary. Binary uses two digits, 0 and 1. Also called as base 2 number system Each position in a binary number represents a 0 power of the base (2). Last position in a binary number represents a x power of the base (2).

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.

Let’s say we have the following floating point number −


Convert decimal 22 to binary 10110. Convert decimal 0.625 to binary 0.101. Combine integer and fraction to get the following output −


Convert floating to binary by taking user input


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))


Enter floating point value :
Enter the number of decimal places of the result :

Updated on: 12-Aug-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started