How format textbox so that "2" becomes "2.00"?

  • Thread starter Thread starter Ronald S. Cook
  • Start date Start date
R

Ronald S. Cook

Stupid q for the day, but if the user enters 2 in a textbox, I want to
display as 2.00.

If they enter 2.129 I want it as 2.13.

I'm guessing will code in the validated method of the textbox, but not sure
how to convert the number.

Thanks for the help.
 
Stupid q for the day, but if the user enters 2 in a textbox, I want to
display as 2.00.

If they enter 2.129 I want it as 2.13.

I'm guessing will code in the validated method of the textbox, but not sure
how to convert the number.

Thanks for the help.
Hi Ronald,

Would something like the following work for you?

protected void Button1_Click(object sender, EventArgs e)
{
double d;

if(double.TryParse(TextBox1.Text, out d))
{
d = Math.Round(d, 2);
Label1.Text = string.Format("{0:.00}", d);
}
}

Also I've posted a link below that has helped me alot with string
formatting

http://blog.stevex.net/index.php/string-formatting-in-csharp/

Happy coding!
 
There are couple of ways doing it...

Use Key_Press event as below on the textbox
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(! (char.IsDigit(e.KeyChar) || e.KeyChar == '.') ) //
use the keys that you want to handle
{
e.Handled = true;
}
}

and also textbox validation event as below

private void textBox1_Validated(object sender, EventArgs e)
{
double d;
if(double.TryParse(textBox1.Text,out d))
{
d = Math.Round(d,2);
textBox1.Text = d.ToString();
}
}

This should solve the problem.

However I would like to derive a class from Textbox and handle the
above events in the derived class and use the same on the form. This
will give you flexibility in the future.

-Cnu
 
if(! (char.IsDigit(e.KeyChar) || e.KeyChar == '.') ) //

But what's with country where number separator is "," not "." like
Poland?
I don't think it is the best resolution.

Regrads
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top