我在数据库中有一个 float 字段。我的应用程序是 WindowsForm。我需要将格式为 43.27 的文本框中的值转换为 double。 当我执行此操作时, 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方法:
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
}
关于c# - 将字符串转换为 Double C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5056554/