Andreas
Andreas

Reputation: 1297

String can't be converted to a double

I have a strange problem. I start by showing the error that I get in a sortLIST function, - which seems strange. The problem occurs for the string "i" as seen in the debug error which is separated by ",". The first argument is 0.48 which is a double. Anyway the error says:

Input string was not in a correct format

I have also tried by remove the CultureInfo("en-Us") line with no success:

enter image description here

Now I have tried to simulate the above and executing this code in a button control and here it DO work and gives no error:

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());
}

What can cause this error? I have put the below line in ALL functions in the application to be on the safe side:

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

Upvotes: 1

Views: 105

Answers (1)

haldo
haldo

Reputation: 16711

The image you uploaded shows you are actually running multiple threads, but the culture is only being set for the current thread.

To overcome this you can assign the desired culture to a variable and use it inside Task.Factory.StartNew. You can do something like this:

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]);
});

As @madreflection pointed out you can just pass the desired culture to double.Parse() method:

// 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);

Or even use CultureInfo.InvariantCulture inside Task.Factory (thanks @Olivier):

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

Upvotes: 4

Related Questions