且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

字符串转换为双C#

更新时间:2023-02-12 17:17:59

尝试解析时指定一个文化:

Try specifying a culture when parsing:

// 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 方式:

And to handle the error case for gracefully instead of throwing exceptions around you could use the TryParse 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
}