Convert string to double or float c#

Kim Andersson picture Kim Andersson · Aug 16, 2014 · Viewed 15.5k times · Source

I need to convert a string to double. Or float, whatever suits best for this type of conversion.

The string is "25.00".

How would I convert this string so that I can use it in calculations?

I've tried with:

string s1 = "2";
string s2 = "25.00";

double d1 = Convert.ToDouble(s1);
double d2 = Convert.ToDouble(s2);
double d3 = d2 * d1;

I've also tried with this:

string s1 = "2";
string s2 = "25.00";

double d1 = double.Parse(s1);
double d2 = double.Parse(s2);
double d3 = d2 * d1;

And:

string s1 = "2";
string s2 = "25.00";

float f1 = float.Parse(s1);
float f2 = float.Parse(s2);
float f3 = f2 * f1;

None of this seem to work, I get a formatexception.

Answer

Jon Skeet picture Jon Skeet · Aug 16, 2014

I suspect your default culture info uses comma as a decimal separator instead of dot. If you know your input will have a dot, it's best to specify the invariant culture explicitly:

double d1 = double.Parse(s1, CultureInfo.InvariantCulture);
double d2 = double.Parse(s2, CultureInfo.InvariantCulture);

However, if the decimal values matter, you should consider using decimal instead of either float or double:

decimal d1 = decimal.Parse(s1, CultureInfo.InvariantCulture);
decimal d2 = decimal.Parse(s2, CultureInfo.InvariantCulture);