Double.Parse - Internationalization problem

oz. picture oz. · Apr 6, 2009 · Viewed 20.5k times · Source

This is driving me crazy. I have the following string in a ASP.NET 2.0 WebForm Page

string s = "0.009";

Simple enough. Now, if my culture is Spanish - which is "es-ES" - and I try to convert the string to Double, I do the following:

double d = Double.Parse(s, new CultureInfo("es-ES"));

what I'd expect is 0,009. Instead, I get 9. I understand that .NET thinks it is a thousand separator, which in en-US is a comma, but shouldn't it take the culture info I'm passing to the parse method and apply the correct format to the conversion?

If I do

double d = 0.009D;
string formatted = d.ToString(new CultureInfo("es-ES"));

formatted is now 0,009. Anybody?

Answer

Jeff Yates picture Jeff Yates · Apr 6, 2009

It is taking the culture you gave and applying the correct formatting. You provided a string of "0.009" and told it that it was Spanish...then you complain that it properly interpreted it as Spanish! Don't tell it that the string is Spanish when you know it isn't.

You should pass the Parse method the culture of the string being parsed, which in this case would be en-US or en-Gb or InvariantCulture.