0

I am trying to format user input to a thousand seperator format. I tried the code here, but it keeps breaking the application:

Amt.Text = String.Format("{0:0,0.00}", Convert.ToDouble(Amt));

So when the user inputs 3566412, then it needs to convert automatically to 3,566,412

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Miss R
  • 23
  • 6

2 Answers2

0

You are trying to convert the control (named Amt) to a double, which is a bad idea since you want to convert the text of the control (Amt.Text). I would suggest to use a decimal since that is more precise and will not cause floating point issues:

Amt.Text = String.Format("{0:0,0.00}", Convert.ToDecimal(Amt.Text));

Another thing to consider is to use a control that can mask itself, so you don't need to replace the text yourself every time.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

You might want to check out Standard Numeric Format Strings at MSDN

Then you could do something like

Amt.Text = inputnumber.ToString("N");

Which will format 3566412 to 3,566,412.0

If you want to take it directly from the textbox, you could do something like this, which checks if the text can be parsed before setting the text

double result = 0;
if (double.TryParse(Amt.Text, out result)
{
    Amt.Text = result.ToString("N");
}
Malte R
  • 468
  • 5
  • 16