1

When I want to convert a string to decimal, I am doing this:

decimal decParseado;
if (decimal.TryParse(txtTexto.Text, out decParseado) == true)
{
    MessageBox.Show("Es decimal: " + decParseado.ToString());
}
else
{
    MessageBox.Show("No es decimal");
}

txtTexto is a textBox in my view. When the user write "12.5" the result is correct, the decimal is 12.5, but when the user write "12,5", the result is 125.

One solution that I am found it is to get the decimal separator from globalization in this way:

string strSeparadorDeCulturaActual = System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;

And then, replace the "," or "." to avoid the user makes a mistake and can to write any of the two characters.

if (strSeparadorDeCulturaActual == ".")
{
    txtTexto.Text= txtTexto.Text.Replace(',', '.');
}
else
{
    txtTexto.Text= txtTexto.Text.Replace('.', ',');
}

But I would like to know if there is a better solution to this problem. I would like that the user, write "," or ".", the parse will be right.

Thank so much.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193
  • 1
    Offtopic: You _should_ name variables in English, otherwise your code becomes a mess to other people(and sometimes yourself). – joppiesaus Jan 01 '15 at 17:26
  • 8
    The correct way is to teach your users that both seperators *are not* exchangable. "1,234" or "1.234" are both perfectly correct numbers. They just have different values. You cannot type garbage in and expect the program to make sense of it. Educate your users. **This is not a software problem**. If decimal.TryParse with your specified localization settings does not parse it, **it's wrong**. – nvoigt Jan 01 '15 at 17:31
  • what about if your users try to enter 1,234.56 ? – Michael Edenfield Jan 01 '15 at 17:55
  • 1
    What you need is this: [Only allow specific characters in textbox](http://stackoverflow.com/questions/12607087/only-allow-specific-characters-in-textbox) – t3chb0t Jan 01 '15 at 17:59

1 Answers1

2

The really, really, really simplest solution would be to prevent the user from typing the , altogather by adding an event handler for the KeyPress event and to put this code there:

if (e.KeyChar == ',')
{
    e.Handled = true;
}
t3chb0t
  • 16,340
  • 13
  • 78
  • 118