Search code examples
c#winformsbinarydecimalwindows-forms-designer

How to solve binary to decimal with fraction in c#? Using winform, Im trying to convert binary numbers into decimal. I used the input function


if (binarybtn.Checked == true)
{
    int decVal = 0, baseVal = 1, rem;
    binarytxtbox.Text = textBox1.Text;

    int input = Convert.ToInt32(textBox1.Text);

    while (input > 0)
    {
        rem     = input % 10;
        decVal  = decVal + rem * baseVal;
        input   = input / 10;
        baseVal = baseVal * 2;
    }

    decimaltxtbox.Text = Convert.ToString(decVal);

    ...

I tried using the input function, but it does not accept strings "."


Solution

  • If I've understood you right, you have a binary number with a fractional part, like

    10.1 (binary)
    

    and you want to convert it into a corresponding decimal number, in the case above it is

    2.5 (decimal)
    

    If it's your task, you can use

    private static decimal BinaryToDecimal(string value, char decimalSeparator = '.') {
      value = value.Trim();
    
      int sign = value.StartsWith('-') ? -1 : 1;
    
      value = value.Trim('-');
    
      int index = value.IndexOf(decimalSeparator);
    
      string integerPart = index >= 0 ? value.Substring(0, index) : value;
    
      decimal result = string.IsNullOrEmpty(integerPart)
        ? 0
        : Convert.ToInt64(integerPart, 2);
    
      string fractionalPart = index >= 0 ? value.Substring(index + 1) : "";
    
      for (int i = 0; i < fractionalPart.Length; ++i)
        result += (decimal)(fractionalPart[i] - '0') / (1L << (i + 1));
    
      return sign * result;
    }
    

    Usage:

    decimaltxtbox.Text = $"{BinaryToDecimal(binarytxtbox.Text)}";
    

    Demo:

    using System.Linq;
    
    ...
    
    string[] tests = {
      "0",
      "-0",
      "100",
      "-100",
      "10.",
      "-10.",
      "1.1",
      "101.101",
      "-101.101",
      ".1011",
      "-.11011",
      "100.00",
      ".", // <- It seems, you treat it as a valid input
    };
    
    string report = string.Join(Environment.NewLine, tests
      .Select(test => $"{test,10} => {BinaryToDecimal(test)}"));
    
    Console.Write(report);
    

    Output:

             0 => 0
            -0 => 0
           100 => 4
          -100 => -4
           10. => 2
          -10. => -2
           1.1 => 1.5
       101.101 => 5.625
      -101.101 => -5.625
         .1011 => 0.6875
       -.11011 => -0.84375
        100.00 => 4
             . => 0  
    

    If you are looking for reverse (i.e. from decimal to binary) conversion, have a look at

    How to convert decimal fractions to hexadecimal fractions?