VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-decimal-fraction-binary-number/

⇱ Convert decimal fraction to binary number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert decimal fraction to binary number

Last Updated : 7 Apr, 2025

Given a fraction decimal number n and integer k, convert decimal number n into equivalent binary number up-to k precision after decimal point. 

Examples:

Input: n = 2.47, k = 5
Output: 10.01111

Input: n = 6.986 k = 8
Output: 110.11111100
We strongly recommend that you click here and practice it, before moving on to the solution.


A) Convert the integral part of decimal to binary equivalent

  1. Divide the decimal number by 2 and store remainders in array. 
  2. Divide the quotient by 2. 
  3. Repeat step 2 until we get the quotient equal to zero.
  4. Equivalent binary number would be reverse of all remainders of step 1.

B) Convert the fractional part of decimal to binary equivalent

  1. Multiply the fractional decimal number by 2. 
  2. Integral part of resultant decimal number will be first digit of fraction binary number. 
  3. Repeat step 1 using only fractional part of decimal number and then step 2. 

C) Combine both integral and fractional part of binary number.

Illustration :

Let's take an example for n = 4.47 k = 3

Step 1: Conversion of 4 to binary
1. 4/2 : Remainder = 0 : Quotient = 2
2. 2/2 : Remainder = 0 : Quotient = 1
3. 1/2 : Remainder = 1 : Quotient = 0

So equivalent binary of integral part of decimal is 100.

Step 2: Conversion of .47 to binary
1. 0.47 * 2 = 0.94, Integral part: 0
2. 0.94 * 2 = 1.88, Integral part: 1
3. 0.88 * 2 = 1.76, Integral part: 1

So equivalent binary of fractional part of decimal is .011

Step 3: Combined the result of step 1 and 2.

Final answer can be written as:
100 + .011 = 100.011

Program to demonstrate above steps: 


Output
100.011
110.11111

Time complexity: O(len(n)) 
Auxiliary space: O(len(n)) 

where len() is the total digits contain in number n.

Comment