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

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

最後一行拋出FormatException,我不知道爲什麼。我想實際上解析字符串來源於此:string.Format(...,double)後跟double.Parse使用相同的NumberFormatInfo將導致FormatException。爲什麼?

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

回答

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

注意,貨幣值通常較好表現爲decimaldouble雖然。

相關問題