2

In my locale the decimal separator is a ','.

However I would still like to write a C# application which works with numbers that use the '.' as decimal separator.

        string b = "0,5";
        double db = double.Parse(b); // gives 0.5

        string a = "0.5";
        double da = double.Parse(a); // gives 5, however i would like to get 0.5
Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
clamp
  • 33,000
  • 75
  • 203
  • 299
  • possible duplicate http://stackoverflow.com/questions/1354924/c-how-do-i-parse-a-string-with-a-decimal-point-to-a-double – Gonzalo.- Sep 14 '12 at 14:56
  • http://stackoverflow.com/questions/2583362/how-to-convert-string-to-double-with-proper-cultureinfo Look here – Borgleader Sep 14 '12 at 14:57

1 Answers1

14

You need to specify the culture as the second argument to double.Parse, e.g.

double da = double.Parse(a, CultureInfo.InvariantCulture);

Pretty much all of the formatting/parsing methods have overloads taking an IFormatProvider, and the most commonly-specified implementation of IFormatProvider is CultureInfo.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • That only works if the value within string was stored using invariant culture. If it wasn't, 0.5 will be parsed as 0.5, while 0,5 will be parsed as 5... It seems that there's no way to get the ultimate solution. – dzendras Feb 12 '13 at 17:51
  • @dzendras: The question states a requirement of "write a C# application which works with numbers that use the '.' as decimal separator" - the answer is meant to meet that requirement. – Jon Skeet Feb 12 '13 at 17:53