Pregunta

i have a simple conversion in C# from string ToDouble as shown in the image. The exception thrown speaks of a datetime conversion, but neither the string resembles a date, not the variable assigned to is a DateTime variable. Can somebody help?

Thank you.

enter image description here

¿Fue útil?

Solución

System.Convert.ToDouble will use double.Parse with the current culture by default. If your decimal separator is not . you might get this exception.

The DateTime thing is misleading since intellisense just tries to help you. Actually it's a number and not a DateTime. So it's not your fault but the Visual-Studio team could improve this message. The FormatException's Message property does not contain DateTime.

It sounds like you want the invariant culture:

double d = double.Parse("0.0005", CultureInfo.InvariantCulture);

If you're not sure if the format is valid you should use double.TryParse:

double d;
if (double.TryParse("0.0005", NumberStyles.Any, CultureInfo.InvariantCulture, out d))
{
    Console.Write("Value is: " + d);
};

Otros consejos

The conversion depends on your country and culture settings.

If your are not in a country that uses a . as a decimal point, you should use CultureInfo.InvariantCulture as a second parameter to your conversion. Alternatively, you can specify the number in your native culture, but that is prone to problems when you give your application to someone using another culture on his PC.

Not sure of why you are getting the error... but have you tried something like this? If so does it give same error?

i.e. double.Parse will use the current culture by default. Have a read of the answer posted by Mr Skeet in this SO post

string sVal ="0.0005"; 
double dVal = 0.0;

if (double.TryParse(sVal, out dVal))
{
    // Success !!
}
else
{
    // Could not convert
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top