0

Hi i'm making an simple c# computation sample Label1.Text = textBox1.Text + textbox2.Text i'm having a problem when i try to input 88.5 or 80.3 and compute my program is keep crashing a getting errors.i already convert the text to Int and here's my code:

 int i;
 i = Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text);
 Label1.Text= i.ToString();

But it's working if i insert 88 and 80 . i know i miss something on this.anyone can help me? thank you

1 Answer 1

5

You're trying to convert "88.5" into an integer. It's not an integer, is it?

I suggest you use decimal instead - and use TryParse so that you can handle invalid user input without resorting to exceptions.

decimal input1, input2;
if (decimal.TryParse(textBox1.Text, out input1) &&
    decimal.TryParse(textBox1.Text, out input2))
{
    Label1.Text = (input1 + input2).ToString();
}
else
{
    Label1.Text = "Invalid input";
}
Sign up to request clarification or add additional context in comments.

6 Comments

@Jay: But do you understand why it works, and the problems of your original code?
yeah sir. Because i only use Integer not decimal
@JonSkeet Sir what if i want to multiply output1 to .20
@Jay: And don't forget to use TryParse ;)
@JonSkeet sir i use this code decimal ans = (output1 * .20) + (output2 * .20); but i get an error.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.