-2

I want to convert a binary fraction into decimal.Consider binary number 1101.1110. I know the manual method of conversion and i can put in the form of program, but i am not able to separate the fractional part from the number. I need to separate it because the method of conversion differs after the point.

while converting decimal to binary the fractional part can be separated this way:

double num=12.23;

int fraction=num-(long)num;

can u help me.

Thanks in advance.

user2821099
  • 39
  • 3
  • 7
  • possible duplicate of [How to split a String in Java](http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – Blorgbeard May 01 '14 at 01:47
  • No, really not a duplicate of that question at all. – Dawood ibn Kareem May 01 '14 at 02:53
  • @DavidWallace " I know the manual method of conversion and i can put in the form of program, but i am not able to separate the fractional part from the number." -> so all he needs is to split the input. – Blorgbeard May 01 '14 at 05:49

3 Answers3

1

I'm assuming you want a result of type double. Parse your String without the point, then divide by the right power of two for the number of digits after the point.

int placesAfterPoint = binaryString.length() - binaryString.indexOf(".") - 1;
long numerator = Long.parseLong(binaryString.replace(".", ""), 2);
double value = ((double) numerator) / ( 1L << placesAfterPoint );
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
0

I would convert your input to a string, get the indexOf the decimal point, remove to a new string all that follows the decimal, truncate the original string to just before the decimal, parse both strings back to you preferred whole number format, then you can do the different methodology on each.

  • In parsing the fractional portion back to a number the order of magnitude of the decimal must be considered. There are many methods to do such. – Mikeologist May 01 '14 at 12:06
0
public class BinaryToDecimal {
    public static double ConvertToDecimal(String a){
    double sum;
                if(a.contains(".")){
            String[] b=a.split("\\.");

            int sum1=Integer.parseInt(b[0],2);


            double sum2=latterPart(b[1]);

            sum=sum1+sum2;

        }else{
            sum=Integer.parseInt(a,2);
        }
        return sum;
}
    public static double latterPart(String number){
            double sum=0;
            int length=number.length();
            for(int i=0;i<length;i++){
                int e=-i-1;
                char mult=number.charAt(i);
                int num=Integer.parseInt(String.valueOf(mult));
                double num1=num*Math.pow(2, e);
                sum=sum+num1;;
            }
        return sum;
    }
}
Chathurika Senani
  • 716
  • 2
  • 9
  • 25