string.Format(…, double) followed by double.Parse using same NumberFormatInfo results in FormatException. Why?

NumberFormatInfo nfi = new NumberFormatInfo()
{
    CurrencySymbol = "$$s. ",
    CurrencyGroupSeparator = ".",
    CurrencyDecimalSeparator = ",",
    NegativeSign = "-",
    CurrencyNegativePattern = 2
};

double amount = double.Parse("$$s. 1.123,00", nfi);

The last line throws a FormatException, and I don't know why. The string I'm trying to parse actually comes from this:

String.Format(nfi, "{0:C}", 1123.00)
Jon Skeet
people
quotationmark

You're not telling it that it should accept a currency value. To do that, you need to call an overload which accepts a NumberStyles value, and include NumberStyles.AllowCurrencySymbol. For example:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        NumberFormatInfo nfi = new NumberFormatInfo()
        {
            CurrencySymbol = "$$s. ",
            CurrencyGroupSeparator = ".",
            CurrencyDecimalSeparator = ",",
            NegativeSign = "-",
            CurrencyNegativePattern = 2
        };

        double d = double.Parse("$$s. 1.123,00",
            NumberStyles.Number | NumberStyles.AllowCurrencySymbol,
            nfi);
        Console.WriteLine(d);
    }
}

Note that currency values are generally better represented as decimal than double though.

people

See more on this question at Stackoverflow