我在数据库中有一个浮动字段。我的应用程序是WindowsForm。我需要将格式 43.27 的文本框中的值转换为双精度。
当我执行此操作 COnvert.ToDouble(txtbox.Text) 时,出现异常,提示输入字符串格式错误。
如何纠正此问题
尝试在解析时指定文化:
// CultureInfo.InvariantCulture would use "." as decimal separator
// which might not be the case of the current culture
// you are using in your application. So this will parse
// values using "." as separator.
double d = double.Parse(txtbox.Text, CultureInfo.InvariantCulture);
为了优雅地处理错误情况,而不是抛出异常,您可以使用TryParse http://msdn.microsoft.com/en-us/library/3s27fasw.aspx method:
double d;
if (double.TryParse(txtbox.Text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
{
// TODO: use the parsed value
}
else
{
// TODO: tell the user to enter a correct number
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)