Convert Decimal fraction to binary in Java

In this section, we are going to learn how to convert a decimal fraction into binary in Java. So, we can divide this problem into two parts i.e one for integral and other for decimal part.

1. To calculate a binary number of an Integral Part:

The logic behind this is to divide the number by two and store its remainder.

  • We will implement a while loop that will work till the time number becomes zero.
  • Divide a number by two and store the remainder in a variable called rem.
  • Update a number to a number divided by two i.e, n=n/2.
  • Insert the remainder at the first index of String.

2. To calculate a binary number of a Fractional Part:

The logic behind this is to multiply the number i.e fractional part by two and store its integral part. In this, we have taken an integer called k which denotes precision up-to k digits. If we have not taken this then in most of the cases the loop will run infinitely.

  • We will implement a while loop that will work till the time k becomes zero.
  • Then, multiply a number by two and store its integral part in a variable called integralPart.
  • Update fractional number by extracting a fractional part of number*2.
  • Lastly, reduce the value of k by one.

Java program to convert Decimal fraction to Binary

package CodeSpeedy;

import java.util.Scanner;

public class decimalToBinary {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    double num,fractionalPart= 0,number;
    int rem=0,integralPart,k;
    StringBuilder s=new StringBuilder();
    Scanner scn=new Scanner(System.in);
    System.out.println("Enter the number");
    num=scn.nextDouble();		//112.564
    System.out.println("Enter number upto which precision is required");
    k=scn.nextInt();			//5
    System.out.print("Output is ");
    int n=(int) num;
    fractionalPart=num-n;
    while(n!=0) {
      rem=n%2;
      n=n/2;
      s.insert(0,rem);
    }
    System.out.print(s+".");
    s=new StringBuilder();
    while(k!=0) {
      integralPart=(int) (fractionalPart*2);
      s.append(integralPart);
      number=fractionalPart*2;
      fractionalPart=number-integralPart;
      k--;
    }
    System.out.println(s);		//1110000.10010
    
  }

}

Output:

Enter the number
112.564
Enter number upto which precision is required
5
Output is 1110000.10010

The catch in this problem is that rather of taking a String, we have used StringBuilder. StringBuilder helps to modify the string from any end which means we can insert an element at any Index which is not supported by normal String. So by using this, we don’t have to implement a function to reverse a String.

Also read: How to convert a HashMap to TreeMap in Java

Leave a Reply

Your email address will not be published. Required fields are marked *