Álvaro García
Álvaro García

Reputation: 19356

How is the best way to convert string to decimal?

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.

Upvotes: 1

Views: 181

Answers (1)

t3chb0t
t3chb0t

Reputation: 18655

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;
}

Upvotes: 2

Related Questions