字符串无法转换为double

问题描述 投票:1回答:1

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

输入字符串的格式不正确

我也尝试删除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");
c# string type-conversion double
1个回答
4
投票

您上传的图像显示您实际上正在运行多个线程,但仅为当前线程设置了区域性。

为了克服这个问题,您可以将所需的文化分配给变量并在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);

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

double test = double.Parse(i.Split(',')[0], CultureInfo.InvariantCulture);
© www.soinside.com 2019 - 2024. All rights reserved.