Python float to binary conversion program

Python Methods and Functions

Suitable:
To convert a decimal floating point number to binary, first convert the integer part to binary, then the fractional part to binary, and finally combine both results to get a definitive answer. 
For the integer part, keep dividing the number by 2 and noting the remainder until the dividend is less than 2. If so, stop and copy all the rest together. 
For the decimal part, keep multiplying the decimal part by 2 until you have 0 as a fractional part. After multiplying for the first time, write down the integral part and again multiply the decimal part of the new value by 2. Continue doing this until you reach the 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:

# Python float converter
# decimal to binary

 
# The function returns octal representation

def float_bin (nu mber, places = 3 ):

 

# split () splits integer and decimal

# part and stores it in two separate variables

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

 

# Convert both integer and decimal

# part from string type to an integer type

whole = int (whole)

dec = int (dec)

 

# Convert integer part of number to

# matching binary and remove

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

res = bin (whole) .lstrip ( "0b" ) + "."

 

# Iterate the number of times we want

# number of decimal places

for x in range (places):

  

# Multiply the decimal value by 2

  # and separate the integer part of the number

  # and decimal part

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

 

# Convert decimal part

# integer again

dec = int (dec)

 

# Continue adding integer parts

  # get the result variable

res + = whole

 

return res

 
# The function converts the value passed as
# parameter to its decimal representation

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 a number
# decimal places the user wants the result as

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

 

print (float_bin (n, places = p))

Exit:

 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  




Get Solution for free from DataCamp guru