Kate
Kate

Reputation: 945

How can I convert textbox value to double in c#?

I am new to c# and using windows forms. I have 2 textboxes textbox1 and textbox2.

Lets say textbox1 has a value of 22, when I click on textbox2, the value in textbox1 should change to double (22.00).

textbox1.text = "22";
private void textBox2_MouseClick(object sender, MouseEventArgs e)
{
    // convert the value in textbox1 to double .
}

Upvotes: 5

Views: 33474

Answers (4)

Yuriy A.
Yuriy A.

Reputation: 752

Double.Parse

Converts the string representation of a number to its double-precision floating-point number equivalent.

Double.TryParse

Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

You should use Double.TryParse instead of Double.Parse to prevent of falling your application by exception if user entered an invalid value.

So, the code would be:

var sourceValue = textBox1.Text;
double doubleValue;
if (double.TryParse(sourceValue, out doubleValue)){
      // Here you already can use a valid double 'doubleValue'
} else {    
      // Here you can display an error message like 'Invalid value'
}

Upvotes: 3

romanoza
romanoza

Reputation: 4862

private void textBox2_MouseClick(object sender, MouseEventArgs e)
{
     // TODO: handle exceptions
     textBox1.Text = double.Parse(textBox1.Text).ToString("F2");
}

1) You can find the format strings here: https://msdn.microsoft.com/pl-pl/library/dwhawy9k(v=vs.110).aspx.

2) double.Parse(...) can throw an exception: https://msdn.microsoft.com/pl-pl/library/fd84bdyt(v=vs.110).aspx

Upvotes: 6

Evgeni Velikov
Evgeni Velikov

Reputation: 382

Try this code

private void textBox2_MouseClick(object sender, MouseEventArgs e)
{
    double number = double.Parse = textbox1.Text;        
    textbox1.Text = double.Parse(Math.Round(number, 2).ToString();
}

where 2 is number of digits after decimal separator

Upvotes: 1

asdfasdfadsf
asdfasdfadsf

Reputation: 391

use the double.Parse() function. Example:

double textBoxValue;
textbox1.Text = "22";
private void textBox2_MouseClick(object sender, MouseEventArgs e)
    {
         textBoxValue = double.Parse(textbox1.Text);
    }

Hope this helps,

Jason.

Upvotes: 1

Related Questions