Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can any one tell how can i format text value of a text box

Tags:

c#

winforms

Hi all i am doing a program to round the text entered in a text box . Sample inputs

Entered value      output value
  100                100.00
   50                 50.00

Like this i would like to format my text box value on textBox1_Leave event

I tried this but didn't work for me

private void textBox1_Leave(object sender, EventArgs e)
{
    string str = string.Format(textBox1.Text, "##.00");
    textBox1.Text = str;
}

Can any one help me

like image 842
Chaitanya Avatar asked Feb 01 '26 23:02

Chaitanya


1 Answers

You'll need to convert that string to an number, then call Format. Also, you were using format incorrectly. You'll need to use a placeholder, like this

string str = String.Format("{0:F2}", Double.Parse(textBox1.Text));
textBox1.Text = str;

Naturally this will puke if you put in non-numeric input. To allow for this, you can do some basic validation

double d = 0;            
textBox1.Text = 
       Double.TryParse(textBox1.Text, out d) ? String.Format("{0:F2}", d) : "0";
like image 194
Adam Rackis Avatar answered Feb 04 '26 11:02

Adam Rackis