4

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?

AgainMe
  • 760
  • 4
  • 13
  • 33
  • Maybe this SO question could help you : http://stackoverflow.com/questions/11560465/parse-strings-to-double-with-comma-and-point – Lucas Delobelle Sep 30 '16 at 10:18

1 Answers1

9

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.
Community
  • 1
  • 1
smoksnes
  • 10,509
  • 4
  • 49
  • 74
  • 2
    I suggest using `CultureInfo.InvariantCulture` instead of a new info for GB-en – king_nak Sep 30 '16 at 10:23
  • @king_nak, yes that is indeed an alternative. However, depending on the server that's executing the code it may not be what you want. http://stackoverflow.com/questions/9760237/what-does-cultureinfo-invariantculture-mean – smoksnes Sep 30 '16 at 10:35
  • 1
    @smoksnes According to https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.invariantculture(v=vs.110).aspx , `InvariantCulture` is associated with the english language. That would be save if you know your input is formatted like this. – king_nak Sep 30 '16 at 10:50
  • I think you mean `"en-GB"` (English, United Kingdom) and `"sv-SE"` (Swedish, Sweden). _Edit:_ `"GB-en"` becomes __Unknown Locale (gb-EN)__. – Jeppe Stig Nielsen Sep 30 '16 at 10:52
  • @king_nak, I stand corrected. I've edited my answer. – smoksnes Sep 30 '16 at 11:44
  • @JeppeStigNielsen, thank you. I've updated my answer. – smoksnes Sep 30 '16 at 11:44