c# - 字符串无法转换为 double

标签 c# string type-conversion double

我有一个奇怪的问题。我首先显示我在 sortLIST 函数中遇到的错误,这看起来很奇怪。如调试错误中所见,字符串“i”出现问题,由“,”分隔。 第一个参数是 0.48,它是一个 double 。无论如何错误说:

输入的字符串格式不正确

我也曾尝试删除 CultureInfo("en-Us") 行,但没有成功:

enter image description here

现在我已经尝试模拟上面的代码并在按钮控件中执行这段代码,在这里它确实有效并且没有给出错误:

private void button1_Click(object sender, EventArgs e)
{
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
    String i = "0.48,trx/btc,coss,hitbtc2,0.0000062000 / 0.0000066000,0.0000061502 / 0.0000061701,,0.48%";
    double test = double.Parse(i.Split(',')[0]);

    MessageBox.Show(test.ToString());
}

什么会导致这个错误?为了安全起见,我在应用程序的所有函数中都添加了以下行:

System.Threading.Thread.CurrentThread.CurrentCulture =
    new System.Globalization.CultureInfo("en-US");

最佳答案

您上传的图像显示您实际上正在运行多个线程,但只为当前线程设置了文化。

为了克服这个问题,您可以将所需的文化分配给一个变量,并在 Task.Factory.StartNew 中使用它。你可以这样做:

var culture = new System.Globalization.CultureInfo("en-US");
return Task.Factory.StartNew(() => 
{
    // use culture here
    Thread.CurrentThread.CurrentCulture = culture;

    // your actual code here
    String i = "0.48,trx/btc,coss,hitbtc2,0.0000062000 / 0.0000066000,0.0000061502 / 0.0000061701,,0.48%";
    double test = double.Parse(i.Split(',')[0]);
});

正如@madreflection 所指出的,您可以将所需的区域性传递给 double.Parse() 方法:

// put this at the top of your file
var culture = new System.Globalization.CultureInfo("en-US");

// use this inside Task.Factory.StartNew
double test = double.Parse(i.Split(',')[0], culture);

甚至在 Task.Factory 中使用 CultureInfo.InvariantCulture(感谢@Olivier):

double test = double.Parse(i.Split(',')[0], CultureInfo.InvariantCulture);

关于c# - 字符串无法转换为 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54935552/

相关文章:

c# - 如何解决 Microsoft.Windows.Storage.StorageException :The remote name could not be resolved

c - 从 char* 到 char[] 的 Srcpy 创建了错误的形式

image - 如何将图像转换为表格

Swift:从字节数据中提取 float

C# 标签和转到

c# - 序列化为 JSON 时如何将属性分组到子对象中

c# - EmguCV 和 UWP - 无法解析程序集或 Windows 元数据文件 'System.Windows.Forms.dll' (Emgu.CV.UI)

c++ - 在字符串中搜索字符

ruby - 计数方法在 Ruby 中如何工作?

postgresql - 使用 JOOQ 工具强制 PostgreSQL 类型转换