【问题标题】:string.Format(…, double) followed by double.Parse using same NumberFormatInfo results in FormatException. Why?string.Format(..., double) 后跟使用相同 NumberFormatInfo 的 double.Parse 会导致 FormatException。为什么?
【发布时间】:2014-10-19 01:17:19
【问题描述】:
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)

【问题讨论】:

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


    【解决方案1】:

    您并不是在告诉它应该接受货币价值。为此,您需要调用一个接受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 更好。

    【讨论】:

      猜你喜欢
      • 2015-04-24
      • 2014-01-27
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多