2

Possible Duplicate:
Reading a double value from a string

I have a problem with converting my String into a double, I always get strange results. I want to convert the following string:

 string Test = "17828.571428571";

I tried it like this (because it normally works):

Double _Test = Convert.ToDouble(Test);

Result is: 17828571428571 (without the dot, lol)

I need it as a double, to Math.Round() afterwards, so I have 17828 in my example. My second idea was to split the string, but is that really the best method? :S

Thanks for helping me!

Finn

Community
  • 1
  • 1

3 Answers3

9

Use InvariantCulture

Double _Test = Convert.ToDouble(Test,CultureInfo.InvariantCulture);

EDIT: I believe your current culture is "German" de-DE, which uses , for floating point.

Tried the following code. You may also use NumberFormatInfo.InvariantInfo during conversion.

string Test = "17828.571428571";
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
double d = Convert.ToDouble(Test);
double d2 = Convert.ToDouble(Test, CultureInfo.InvariantCulture);
double d3 =  Convert.ToDouble(Test, NumberFormatInfo.InvariantInfo);

string Test2 = "17828,571428571"; //Notice the comma in the string
double d4 = Convert.ToDouble(Test2);
Console.WriteLine("Using comma as decimal point: "+ d4);

Output: (Notice the comma in the output)

Wihtout Invariant: 17828571428571
With InvariantCulture: 17828,571428571
With NumberFormatInfo.InvariantInfo: 17828,571428571
Using comma as decimal point: 17828,571428571
Habib
  • 219,104
  • 29
  • 407
  • 436
4

Try Double.TryParse or Double.Parse if you are sure there is the correct format

EDIT: But take care of the format. as example if you are german you need to type 140,50 and not 140.50 because 140.50 would be 14050. Or you pass as parameter that you dont care of culture (see other posts).

Florian
  • 5,918
  • 3
  • 47
  • 86
4
double _Test = double.Parse(Test,CultureInfo.InvariantCulture);

You need to set the format provider of the conversion operation to invariant.

daryal
  • 14,643
  • 4
  • 38
  • 54