Double.Parse - Internationalization problem

前端 未结 6 660
故里飘歌
故里飘歌 2020-12-17 10:04

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

相关标签:
6条回答
  • 2020-12-17 10:47

    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 ;)

    0 讨论(0)
  • 2020-12-17 10:47
    double d = Double.Parse("0,009",
        NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands,
        CultureInfo.CreateSpecificCulture("es-ES"));
    

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

    0 讨论(0)
  • 2020-12-17 10:53

    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.

    0 讨论(0)
  • 2020-12-17 10:55

    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.

    0 讨论(0)
  • 2020-12-17 11:01

    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.

    0 讨论(0)
  • 2020-12-17 11:05

    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.

    0 讨论(0)
提交回复
热议问题