Convert Decimal fraction to binary in Python
In this tutorial, we will show you how to convert decimal fraction to binary in Python.
Note:
- Here, we are going to convert a decimal number into its equivalent binary number up to k-precisions(number of digits after the decimal point).
- k will be given by the user as an input in addition to the decimal number.
Python Program to Convert Decimal fraction to binary
This program contains 3 parts.
- Converting an integral part of decimal to binary equivalent.
- Converting the fraction part of decimal to binary equivalent.
- Combining both the integral and fraction part of the binary number.
Algorithm:
1. Converting an integral part of decimal to the binary equivalent
- Divide the integer by 2 and keep track of the remainder.
- Divide the quotient by 2 until you get quotient as zero.
- Finally, stored remainders are reversed to get the equivalent binary number.
2. Converting the fraction part of decimal to the binary equivalent
- Multiply the fraction part of the decimal number by 2.
- Store the integer part of the resultant decimal number.
- Repeat step 1 and step 2 for k(precisions after decimal point) times.
3. Then combine both the integral and fraction part of the binary.
Now, we have a look at the implementation of the above algorithm.
def decToBinConversion(no, precision): binary = "" IntegralPart = int(no) fractionalPart = no- IntegralPart #to convert an integral part to binary equivalent while (IntegralPart): re = IntegralPart % 2 binary += str(re) IntegralPart //= 2 binary = binary[ : : -1] binary += '.' #to convert an fractional part to binary equivalent while (precision): fractionalPart *= 2 bit = int(fractionalPart) if (bit == 1) : fractionalPart -= bit binary += '1' else : binary += '0' precision -= 1 return binary no = float(input()) k = int(input()) print("Binary Equivalent:",decToBinConversion(no,k))
Sample output 1:
38.67 3 Binary Equivalent: 100110.101
Sample output 2:
8.45 2 Binary Equivalent: 1000.01
I hope that this tutorial has taught you something useful.
Leave a Reply