string.Format(...,double)后跟double.Parse使用相同的NumberFormatInfo导致FormatException。为什么?

时间:2014-10-18 17:03:27

标签: c# string double string-parsing string.format

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

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

最后一行抛出一个FormatException,我不知道为什么。我试图解析的字符串实际上来自:

String.Format(nfi, "{0:C}", 1123.00)

1 个答案:

答案 0 :(得分:3)

您没有告诉它应该接受货币值。为此,您需要调用一个接受NumberStyles值的重载,并包含NumberStyles.AllowCurrencySymbol。例如:

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

请注意,货币值通常更好地表示为decimal而不是double