Search code examples
c#.netparsingdoubleculture

C# double.TryParse with InvariantCulture returns unexpected result


I'm trying to unit test a getprice method using NUnit. I am stuck with parsing the rawprice into double. My cultureinfo is en-US but I set it to de-DE for this test. Double parsing with numberstyles.any and invariantculture returns unexpected result.

The rawprice cultureinfo is unknown, it can be any. Also the server where it will run is also unknown and can be in any language.

For this test, I tried German for the rawprice and machine.

I tried parsing "9,42" but the result is 942.

[Test]
[SetCulture("de-DE")]
public void GetPrice_PriceTextWithCommaDecimal_ReturnsInvariantPrice()
{
    var rawPriceText = "9,42";
    double.TryParse(rawPriceText, NumberStyles.Any, CultureInfo.InvariantCulture, out double price);
    //parsed price result is 942

    ...
}

Solution

  • It's not clear from your question what you expected. However, as far as what the code is doing, it's doing exactly what you told it to:

    • Providing NumberStyles.Any tells double.TryParse() to allow any format, except AllowHexSpecifier. This includes the AllowThousands option.
    • Providing the InvariantCulture causes parsing to use the ',' character as the thousands separator.
    • Parsing doesn't actually care where a thousands separator appears. I.e. it doesn't actually force the separator to be in the location where it would indicate a thousands-multiple digit.

    So, when you ask it to parse "9,42", that text is interpreted using InvariantCulture (i.e. ignoring your current culture of de-DE), the ',' character is treated as a thousands separator (i.e. ignored for the purpose of computing the actual value), and you get the value 942, just like you asked for.

    If you don't want that result, you need to use different arguments for the call to double.TryParse(). You would need to explain what you do want if you want advice on what arguments you should use. All we can say given the information currently in your question is what arguments you apparently don't want.