By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,241 Members | 760 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,241 IT Pros & Developers. It's quick & easy.

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

P: n/a
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.

Jun 1 '08 #1
Share this Question
Share on Google+
3 Replies


P: n/a
M#
On Jun 1, 4:27 pm, "Ronald S. Cook" <rc...@westinis.comwrote:
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/str...ing-in-csharp/

Happy coding!
Jun 2 '08 #2

P: n/a
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

On Jun 2, 1:27*am, "Ronald S. Cook" <rc...@westinis.comwrote:
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.
Jun 2 '08 #3

P: n/a
On Jun 2, 8:44 am, Duggi <DuggiSrinivasa...@gmail.comwrote:
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
Jun 2 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.