将字符串转换为Double C#

xar*_*ria 3 c# sql type-conversion

我在DB中有一个浮点数字段.我的应用程序是WindowsForm.我需要将格式为43.27的文本框中的值转换为double.当我这样做COnvert.ToDouble(txtbox.Text)我得到异常,说输入字符串是错误的格式.如何纠正这个问题

Dar*_*rov 10

尝试解析时指定文化:

// 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);
Run Code Online (Sandbox Code Playgroud)

并且为了优雅地处理错误情况而不是抛出异常,可以使用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
}
Run Code Online (Sandbox Code Playgroud)