Enter fractions textbox C #

1

I have to make a program that solves the determinant of a matrix, n11 = double.Parse(b11.Text); and works well with integers. But I also want it to work if I enter numbers like 1/4, 3/16 and so on. How can I have him read the fraction to perform the operation? Thank you very much

    
asked by Oscar Rojas 16.03.2018 в 05:25
source

1 answer

1

You have to use String.Split

string[] aux;
double resultado;
if (textBox1.Text.Contains("/"))
{
    aux = textBox1.Text.Split(new char[] { '/' }, 2);
    resultado = double.Parse(aux[0]) / double.Parse(aux[1]);
}
else
{
    resultado = double.Parse(textBox1.Text);
}

MessageBox.Show(resultado.ToString());

EDIT: In the case that you need to be able to enter more complex fractions like 3/4/6 you can do the following ..

string[] aux;
double resultado=0;

if (textBox1.Text.Contains("/"))
{
      aux = textBox1.Text.Split(new char[] { '/' }, textBox1.Text.Length-1);
      resultado = double.Parse(aux[0]);
      foreach(string numero in aux.Skip(1))
      {
      resultado /= double.Parse(numero);                    
      }
}
else
{
        resultado = double.Parse(textBox1.Text);
}



MessageBox.Show(resultado.ToString());

It is possible that there is a simpler way to solve it, but it is the first thing that occurred to me, greetings!

    
answered by 16.03.2018 / 13:48
source