c# - 将字符串转换为 Double C#

标签 c# sql type-conversion

我在数据库中有一个 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/

相关文章:

c# - 如何从我的代码隐藏中访问 XAML 对象的绑定(bind)属性?

c# - 使用 Javascript 折叠 RadFileExplorer

c# - 将数字转换为 .NET 中的十六进制值

mysql - sql查询中where子句中n的用途是什么

sql - 在oracle sql中加入sql View

Java 无法获取正确的 var 值

c - 在 float 的右侧添加零

c# - 处理方法中的已知错误和错误消息

php - 按另一个表中的帖子排序

c++ - 专门的 shared_ptr 转换 C++0x