Converting String to Double or Int

I am working on creating a program that calculates the area of a rectangle.

The program has two textboxes and a button. When the button is pressed, I need to convert the strings to numbers according to type (ie if it's a double, i need it to be a double...integer to int)

In my class file, I have three constructors

1. Takes two integers <-returns integer
2. Takes two doubles <-returns double
3. Takes an integer and a double <- returns double

I tried writing something similar to what is below to try to define the variables but it didn't work.

if (textbox1.text.contains(".")
double width = Convert.ToDouble(textbox1.text);
else
int width = Convert.ToInt32(textbox1.text);

That seemed pretty silly and the compiler seemed to think so too. I know there is an easier way to do this, I'm just not sure what it is.

Any help would be greatly appreciated.





Answer this question

Converting String to Double or Int

  • muntyanu

    hi,

    tryparse will return a boolean value repressed the success of the conversion operation

    you can do something like that when the user submit his answes


    double var1, var2;
    if (!double.TryParse(TextBox1.Text, out var1))
    {
    MessageBox.Show("text box 1 should have numbers only");
    return;
    }
    // the same for textbox2


     

    hope this helps



  • saktya

    new string stringname = Converter.ToDouble(stringobject name);

    Forget building constructors that take integers, even if an integer is entered, it is OK to treat it as a double.

    I would only use an integer in a situation where I know that under no circumstances will the values being entered have a decimal, for instance, how many Children do you have the response can only be an integer (even then you would test that the entry is an integer within the code or cast it as an integer).

    A double is suitable to handle doubles and/or integers.

    Furthermore the data entered will be decided (as either an integer or decimal) at run time, so when would you ever use a constructor that takes an integer

    Keep it simple and use the function(double, double) constructor.

    Have Fun!.


  • odomae

    Only convert it into double, no need to check for '.', and whenever you pass this double value to the constructor having int argument, the compiler will cast it into int by himself.



  • Converting String to Double or Int