3

I have a simple console application in visual studio for testing some code before going big. But now i have a problem with parsing some string to double.
When the users input is a String: 0.10 i want to convert this to a double. So the output should be a double: 0.10.

But when i do this with the following code:

double r_value = 0;
r_value = Math.Round(double.Parse(value), 2);

Or

r_value = double.Parse(value);

The output will be: 10 or 10.0. How can it be this output changes like this? and converts to 10.0 instead 0.10 as i thought it should be.

Dion Segijn
  • 2,625
  • 4
  • 24
  • 41
  • Where is value set? That's possibly one of the more important parts of this and you've left it out. – Hoeloe Dec 11 '12 at 21:00
  • 2
    Are the number settins in the computer set correctly? I mean, isn't the computer set to use commas instead of dots? – PedroC88 Dec 11 '12 at 21:01

1 Answers1

13

I strongly suspect your default culture is one in which . is a grouping separator (usually for thousands). So where an English person might write ten thousand as "10,000" some other cultures would write "10.000". At that point, your output makes sense.

If you want to parse with the invariant culture (which treats . as a decimal separator and , as the grouping separator) do so explicitly:

double r_value = double.Parse(value, CultureInfo.InvariantCulture);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Would `Convert.ToDouble()` work as well? Or is that Culture dependent too? – Bob. Dec 11 '12 at 21:01
  • Yes you are absolutely right! my bad. Thanks for your fast response, and in the right column i now see this question: http://stackoverflow.com/questions/11455306/why-double-parse0-05-returns-5-0?rq=1 (but did not found it before posting). – Dion Segijn Dec 11 '12 at 21:02
  • 4
    @Bob: From the docs for `Convert.ToDouble(string)`: "Using the ToDouble(String) method is equivalent to passing value to the Double.Parse(String) method. value is interpreted by using the formatting conventions of the current thread culture." – Jon Skeet Dec 11 '12 at 21:03
  • @Bob `Convert.ToDouble` (like `double.Parse`) has an overload that takes in a format provider (like a `CultureInfo`). If you set `provider` to `null`, or equivalently call the overload with no `provider` parameter, the `CurrentCulture` is used. – Jeppe Stig Nielsen Dec 11 '12 at 22:12