AgainMe AgainMe - 2 months ago 8
C# Question

Double.Parse cannot keep comma

I'm trying to convert a string into double, I've this value:

53.095
and try to convert into double as:

string doub = "53.095";
var cv = Convert.ToDouble(doub);


I get:
53095
. Why I doesn't get the comma? What am I missing?

Answer

I guess it's because different countries handle comma differently. My country, for example uses , instead. So you must be aware of how the string is formatted.

string doub = "53.095";
var cv = double.Parse(doub, new CultureInfo("en-GB"));

For another localization this will work.

string doub = "53,095"; // note ,
var cv = double.Parse(doub, new CultureInfo("sv-SE"));

EDIT:

As king_nak mentioned, you will be able to use CultureInfo.InvariantCulture as long as you're using the english style for formatting.

[...] it is associated with the English language but not with any country/region.

string doub = "53.095";
string doub2 = "53,095"; 
var cv1 = double.Parse(doub, CultureInfo.InvariantCulture); // Works
var cv2 = double.Parse(doub2, CultureInfo.InvariantCulture); // Does not work.