Double.Parse - Internationalization problem

半腔热情 提交于 2019-11-29 05:36:54

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.

what Jess's writing works for me. just for anyone who'd need to try out how to get "invariant culture": it looks this

double d = Double.Parse(myString, CultureInfo.InvariantCulture);

(first stackoverflow post, so yea, rather marginal ;)

You have it backwards.

When you say double d = Double.Parse(s, new CultureInfo("es-ES"));, you are asking .NET to parse your string into a double, assuming that the string is written in the es-ES culture.

In Spanish culture, "." is a thousands separator, so "0.009" is 9.

When you convert using ToString(), at the end, it's saying convert 0.009 to a string using the spanish culture, so it uses "," as the decimal separator, and you get "0,009". The behavior is correct.

My guess is that you want to use Double.Parse with the Invariant Culture, and ToString with the spanish culture, so 0.009 becomes 0,009.

I think you are interpreting it the wrong way around, in es-ES culture 0.009 is really just a long way of saying 9, as the "." is not the decimal separator, so if you ask for the string "0.009" to be parsed with the es-ES culture you should indeed get the deouble 9.0. If you ask it to parse "0,009" you should get a double of 0.009.

Similarly, if you ask it to format the double 0.009 you should get the string "0,009" in es-ES.

You're mistaking parsing and formatting. You get 9 instead of .009 the first time because you take a string that is formated in a .-based culture and parse it using a ,-based culture. You need to parse it using whatever culture it was created with and then format it using whatever culture you want for display.

double d = Double.Parse("0,009",
    NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands,
    CultureInfo.CreateSpecificCulture("es-ES"));

In es-ES culture "," is a decimal seporator (not ".")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!