I'm trying to convert this string to double
Convert.ToDouble("1.12");
and this is the output
System.FormatException was unhandled.
Should I do something like this?
public static double ConvertToDouble(string ParseVersion)
{
double NewestVersion;
try
{
NewestVersion = Convert.ToDouble(ParseVersion);
}
catch
{
ParseVersion = ParseVersion.Replace('.', ',');
NewestVersion = Convert.ToDouble(ParseVersion);
}
return NewestVersion;
}
ConvertToDouble("1.12");
Or is there an easier solution?
You don't have to replace
.
to,
.. however a better way is to use the .netTryParse
method like:Edit: Also note that by replacing
.
by,
you are getting a wrong results, for instance1.12
:double.Parse
will use the current culture by default. It sounds like you want the invariant culture:EDIT: Just to be clear, obviously you shouldn't use this if you're trying to parse text entered by a user in a different culture. This is for use when you've received data in the invariant culture (as most machine-to-machine data text-based formats are) and want to enforce that when parsing.
Convert.ToDouble uses Double.Parse internally. If you are unsure of the culture context, you should use an overload of Double.Parse precising the culture:
Keep in mind, this problem can depend on where the input string comes from. If it is read from a database as an object, you might solve your problem by keeping it as an object and using Convert.ToDouble() as follows: