Type conversion problem

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

This should be simple, but either I'm blind, stupid or going mad.

I'm trying to convert a string, containing a numeric value to a double (in
C#), but when I run the code below I get the error message "Input string was
not in a correct format." Why?

string s = "8.0";
double d = Convert.ToDouble(s);
 
henfo said:
This should be simple, but either I'm blind, stupid or going mad.

I'm trying to convert a string, containing a numeric value to a double (in
C#), but when I run the code below I get the error message "Input string
was
not in a correct format." Why?

string s = "8.0";
double d = Convert.ToDouble(s);

The code you posted here works fine for me in the context of a simple
console application in Visual Studio 2003. Please describe the environment
surrounding the failure.
 
Thanks for your reply.

I too am working in Visual Studio 2003 and tried the code lines in a
console application before posting. I installed the software a couple of
months ago and have been working in it more or less daily since then and
haven't run in to any other strange problems.

\Henrik
 
henfo said:
This should be simple, but either I'm blind, stupid or going mad.

I'm trying to convert a string, containing a numeric value to a double (in
C#), but when I run the code below I get the error message "Input string was
not in a correct format." Why?

string s = "8.0";
double d = Convert.ToDouble(s);

I suspect the problem is the locale you're running in. Try this:

using System;
using System.Threading;
using System.Globalization;

public class Test
{
static void Main()
{
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture("en");
Console.WriteLine (Convert.ToDouble("8.0"));
}
}

Now change the "en" to "fr" and run it again, and you'll see the error.

If you want to do the conversion in the invariant culture, do:

Convert.ToDouble(s, CultureInfo.InvariantCulture);
 
Back
Top