将字符串转换为十进制的最佳方法是什么?

How is the best way to convert string to decimal?

当我想将字符串转换为十进制时,我是这样做的:

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

txtTexto 在我看来是一个文本框。当用户写“12.5”结果是正确的,小数点是12.5,但是当用户写“12,5”时,结果是125.

我发现的一种解决方案是通过这种方式从全球化中获取小数点分隔符:

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

然后,替换“,”或“.”为避免用户写错,可以写任意两个字符。

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

但是我想知道是否有更好的方法来解决这个问题。我希望用户,写“,”或“。”,解析将是正确的。

非常感谢。

真正非常非常简单的解决方案是通过为 KeyPress 事件添加一个事件处理程序来阻止用户键入 , 总计,并将此代码放在那里:

if (e.KeyChar == ',')
{
    e.Handled = true;
}