Conversion of binary fraction to decimal in Java

In this section, we are going to learn how to convert Binary to Decimal in Java. So, we can divide this problem into two parts i.e one for calculation of integral part and other for decimal part. Firstly, we need to partition an integral and fractional part of a binary number. For that, we have simply used a String function called indexOf which will return the index of the first occurrence of the specified substring i.e. point/dot (.), and store its value in the variable called index.

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

  • We will iterate over the String in reverse order using for loop from index-1 to the first element.
  • Store element at each index in a variable called number.
  • Multiply this number with a power of two and store its value in a variable called temp.
  • Update an Integral part with the summation of previously stored value and temp.
  • Increment count by one.

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

  • First, we will iterate over the String using for loop from index+1 to the last element.
  • Store element at each index in a variable called number.
  • Multiply this number with a power of two and store its value in a variable called temp.
  • Update a Fractional part with the summation of previously stored value and temp.
  • Decrement counter by one.

The summation of the Integral and Fractional part results in an answer.

Java program to convert Binary fraction to Decimal

package CodeSpeedy;

import java.util.Scanner;

public class binaryToDecimal {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    int count=0,index=0, integralPart=0,counter=-1;
    double fractionalPart=0;
    Scanner scn=new Scanner(System.in);
    System.out.println("Enter a binary number");
    String s=scn.next();  //1001.1101001
    index=s.indexOf(".");
    for(int i=index-1;i>=0;i--) {
      int number=s.charAt(i)-'0';
      double temp=number*Math.pow(2,count);
      integralPart+=temp;
      count++;
    }
    
    for(int i=index+1;i<s.length();i++) {
      int number=s.charAt(i)-'0';
      double temp=number*Math.pow(2, counter);
      fractionalPart+=temp;
      counter--;
    }
    fractionalPart+=integralPart;
    System.out.print("The Output is: ");
    System.out.print(fractionalPart);
  }

}

Output:

Enter a binary number
1001.1101001
The Output is: 9.8203125

The catch in this problem is that instead of taking a double number,  we have used a String to hold a value of the number to avoid floating-point errors and rounding off numbers that cause fallacy in our result.

Also read: Convert Decimal fraction to binary in Java

Leave a Reply

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