共用方式為


剖析數值字串

更新:2010 年 8 月

所有數值型別都有兩個靜態剖析方法 Parse 和 TryParse,您可以使用這兩種方法將數字的字串表示轉換成數字型別。 這些方法可讓您剖析使用標準數值格式字串自訂數值格式字串中記載的格式字串所產生的字串。 根據域設,Parse 和 TryParse 方法能夠成功將只包含整數十進位數字的字串轉換成整數值。 這兩種方法可成功將包含整數和小數十進位數字、群組分隔符號和小數分隔符號的字串轉換成浮點值。 如果作業失敗,Parse 方法會擲回例外狀況,而 TryParse 方法會傳回 false。

剖析和格式提供者

通常數值的字串表示會因文化特性而異。 數值字串的項目都會因文化特性而有所不同,包括貨幣符號、群組 (或千分位) 分隔符號和小數分隔符號。 剖析方法會隱含或明確地使用辨識這些文化特性專屬變化的格式提供者。 如果 Parse 或 TryParse 的呼叫中未指定格式提供者,則會使用與目前執行緒文化特性 (NumberFormatInfo.CurrentInfo 屬性傳回的 NumberFormatInfo 物件) 相關聯的格式提供者。

格式提供者是由 IFormatProvider 實作表示。 這個介面擁有單一成員,也就是 GetFormat 方法,其單一參數為代表要格式化之型別的 Type 物件。 這個方法會傳回提供格式資訊的物件。 .NET Framework 支援下面兩個剖析數值字串的 IFormatProvider 實作:

下列範例會嘗試將陣列中的每個字串轉換成 Double 值。 它會先嘗試使用反映英文 (美國) 文化特性之慣例的格式提供者剖析字串。 如果這個作業擲回 FormatException,它會先嘗試使用反映法文 (法國) 文化特性之慣例的格式提供者剖析字串。

Imports System.Globalization

Module Example
   Public Sub Main()
      Dim values() As String = { "1,304.16", "$1,456.78", "1,094", "152", 
                                 "123,45 €", "1 304,16", "Ae9f" }
      Dim number As Double
      Dim culture As CultureInfo = Nothing

      For Each value As String In values
         Try
            culture = CultureInfo.CreateSpecificCulture("en-US")
            number = Double.Parse(value, culture)
            Console.WriteLine("{0}: {1} --> {2}", culture.Name, value, number)
         Catch e As FormatException
            Console.WriteLine("{0}: Unable to parse '{1}'.", 
                              culture.Name, value)
            culture = CultureInfo.CreateSpecificCulture("fr-FR")
            Try
               number = Double.Parse(value, culture)
               Console.WriteLine("{0}: {1} --> {2}", culture.Name, value, number)
            Catch ex As FormatException
               Console.WriteLine("{0}: Unable to parse '{1}'.", 
                                 culture.Name, value)
            End Try
         End Try
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output:
'    en-US: 1,304.16 --> 1304.16
'    
'    en-US: Unable to parse '$1,456.78'.
'    fr-FR: Unable to parse '$1,456.78'.
'    
'    en-US: 1,094 --> 1094
'    
'    en-US: 152 --> 152
'    
'    en-US: Unable to parse '123,45 €'.
'    fr-FR: Unable to parse '123,45 €'.
'    
'    en-US: Unable to parse '1 304,16'.
'    fr-FR: 1 304,16 --> 1304.16
'    
'    en-US: Unable to parse 'Ae9f'.
'    fr-FR: Unable to parse 'Ae9f'.
'    ' The example displays the following output:
'    en-US: 1,304.16 --> 1304.16
'    
'    en-US: Unable to parse '$1,456.78'.
'    fr-FR: Unable to parse '$1,456.78'.
'    
'    en-US: 1,094 --> 1094
'    
'    en-US: 152 --> 152
'    
'    en-US: Unable to parse '123,45 €'.
'    fr-FR: Unable to parse '123,45 €'.
'    
'    en-US: Unable to parse '1 304,16'.
'    fr-FR: 1 304,16 --> 1304.16
'    
'    en-US: Unable to parse 'Ae9f'.
'    fr-FR: Unable to parse 'Ae9f'.
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] values = { "1,304.16", "$1,456.78", "1,094", "152", 
                          "123,45 €", "1 304,16", "Ae9f" };
      double number;
      CultureInfo culture = null;

      foreach (string value in values) {
         try {
            culture = CultureInfo.CreateSpecificCulture("en-US");
            number = Double.Parse(value, culture);
            Console.WriteLine("{0}: {1} --> {2}", culture.Name, value, number);
         }   
         catch (FormatException) {
            Console.WriteLine("{0}: Unable to parse '{1}'.", 
                              culture.Name, value);
            culture = CultureInfo.CreateSpecificCulture("fr-FR");
            try {
               number = Double.Parse(value, culture);
               Console.WriteLine("{0}: {1} --> {2}", culture.Name, value, number);
            }
            catch (FormatException) {
               Console.WriteLine("{0}: Unable to parse '{1}'.", 
                                 culture.Name, value);
            }
         }
         Console.WriteLine();
      }   
   }
}
// The example displays the following output:
//    en-US: 1,304.16 --> 1304.16
//    
//    en-US: Unable to parse '$1,456.78'.
//    fr-FR: Unable to parse '$1,456.78'.
//    
//    en-US: 1,094 --> 1094
//    
//    en-US: 152 --> 152
//    
//    en-US: Unable to parse '123,45 €'.
//    fr-FR: Unable to parse '123,45 €'.
//    
//    en-US: Unable to parse '1 304,16'.
//    fr-FR: 1 304,16 --> 1304.16
//    
//    en-US: Unable to parse 'Ae9f'.
//    fr-FR: Unable to parse 'Ae9f'.

剖析和 NumberStyles 值

剖析作業可以處理的樣式項目 (例如泛空白字元、群組分隔符號和小數分隔符號) 是由 NumberStyles 列舉值所定義。 根據預設,代表整數值的字串是使用 NumberStyles.Integer 值剖析,這樣只會允許數字、前置和尾端空白字元,以及前置正負號。 代表浮點值的字串是使用 NumberStyles.FloatNumberStyles.AllowThousands 值的組合進行剖析,這個複合樣式允許十進位數字與前置和尾端空白字元、前置正負號、小數分隔符號、群組分隔符號及指數。 藉由呼叫包含 NumberStyles 型別之參數的 Parse 或 TryParse 方法多載,以及設定一個或多個 NumberStyles 旗標,您就可以控制能夠出現在字串中,使剖析作業成功的樣式項目。

例如,包含群組分隔符號的字串無法使用 Int32.Parse(String) 轉換成 Int32。不過,如果您使用 NumberStyles.AllowThousands 旗標,轉換就會成功,如下列範例所述。

Imports System.Globalization

Module Example
   Public Sub Main()
      Dim value As String = "1,304"
      Dim number As Integer
      Dim provider As IFormatProvider = CultureInfo.CreateSpecificCulture("en-US")
      If Int32.TryParse(value, number) Then
         Console.WriteLine("{0} --> {1}", value, number)
      Else
         Console.WriteLine("Unable to convert '{0}'", value)
      End If

      If Int32.TryParse(value, NumberStyles.Integer Or NumberStyles.AllowThousands, 
                        provider, number) Then
         Console.WriteLine("{0} --> {1}", value, number)
      Else
         Console.WriteLine("Unable to convert '{0}'", value)
      End If
   End Sub
End Module
' The example displays the following output:
'       Unable to convert '1,304'
'       1,304 --> 1304
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string value = "1,304";
      int number;
      IFormatProvider provider = CultureInfo.CreateSpecificCulture("en-US");
      if (Int32.TryParse(value, out number))
         Console.WriteLine("{0} --> {1}", value, number);
      else
         Console.WriteLine("Unable to convert '{0}'", value);

      if (Int32.TryParse(value, NumberStyles.Integer | NumberStyles.AllowThousands, 
                        provider, out number))
         Console.WriteLine("{0} --> {1}", value, number);
      else
         Console.WriteLine("Unable to convert '{0}'", value);
   }
}
// The example displays the following output:
//       Unable to convert '1,304'
//       1,304 --> 1304
注意事項警告

剖析作業永遠使用特定文化特性的格式慣例。如果您不是用傳遞 CultureInfoNumberFormatInfo 物件的方式來指定文化特性,則會使用與目前執行緒相關聯的文化特性。

下表列出 NumberStyles 列舉型別的成員,並且描述這些成員對剖析作業的影響。

NumberStyles 值

對於要剖析之字串的影響

NumberStyles.None

只允許數字。

NumberStyles.AllowDecimalPoint

允許小數分隔符號和小數點後數字。 若為整數值,則僅允許零做為小數點後數字。 有效的小數分隔符號是由 NumberFormatInfo.NumberDecimalSeparatorNumberFormatInfo.CurrencyDecimalSeparator 屬性決定。

NumberStyles.AllowExponent

"e" 或 "E" 字元可以用來表示指數標記法。 如需詳細資訊,請參閱 NumberStyles

NumberStyles.AllowLeadingWhite

允許前置空白字元。

NumberStyles.AllowTrailingWhite

允許尾端空白字元。

NumberStyles.AllowLeadingSign

數字前面可以加上正負號。

NumberStyles.AllowTrailingSign

數字後面可以加上正負號。

NumberStyles.AllowParentheses

可以使用括號表示負值。

NumberStyles.AllowThousands

允許群組分隔符號。 群組分隔符號字元是由 NumberFormatInfo.NumberGroupSeparatorNumberFormatInfo.CurrencyGroupSeparator 屬性決定。

NumberStyles.AllowCurrencySymbol

允許貨幣符號。 貨幣符號是由 NumberFormatInfo.CurrencySymbol 屬性所定義。

NumberStyles.AllowHexSpecifier

要剖析的字串會解譯為十六進位數字。 該字串可包含十六進位數字 0-9、A-F 和 a-f。 這個旗標只可用來剖析整數值。

此外,NumberStyles 列舉型別還提供下列複合樣式,這些樣式中包括多個 NumberStyles 旗標。

複合的 NumberStyles 值

包括成員

NumberStyles.Integer

包括 NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhiteNumberStyles.AllowLeadingSign 樣式。 這是用來剖析整數值的預設樣式。

NumberStyles.Number

包括 NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhiteNumberStyles.AllowLeadingSignNumberStyles.AllowTrailingSignNumberStyles.AllowDecimalPointNumberStyles.AllowThousands 樣式。

NumberStyles.Float

包括 NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhiteNumberStyles.AllowLeadingSignNumberStyles.AllowDecimalPointNumberStyles.AllowExponent 樣式。

NumberStyles.Currency

包括所有樣式,除了 NumberStyles.AllowExponentNumberStyles.AllowHexSpecifier 之外。

NumberStyles.Any

包括所有樣式,除了 NumberStyles.AllowHexSpecifier 之外。

NumberStyles.HexNumber

包括 NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhiteNumberStyles.AllowHexSpecifier 樣式。

剖析和 Unicode 數字

Unicode 標準會定義各種書寫系統中數字的字碼指標。 例如,U+0030 到 U+0039 的字碼指標表示基本拉丁文數字 0 到 9,U+09E6 到 U+09EF 字碼指標表示孟加拉文數字 0 到 9,而 U+FF10 到 U+FF19 字碼指數表示全形數字 0 到 9。 不過,剖析方法唯一能夠辨識的數字為字碼指標 U+0030 到 U+0039 的基本拉丁數字 0 到 9。 如果傳遞包含任何其他數字的字串給數值剖析方法,則該方法會擲回 FormatException

下列範例使用 Int32.Parse 方法剖析由不同書寫系統的數字所組成的字串。 如範例的輸出所示,嘗試剖析基本拉丁數字會成功,而嘗試剖析全型、阿拉伯-印度和孟加拉數字則會失敗。

Module Example
   Public Sub Main()
      Dim value As String
      ' Define a string of basic Latin digits 1-5.
      value = ChrW(&h31) + ChrW(&h32) + ChrW(&h33) + ChrW(&h34) + ChrW(&h35)
      ParseDigits(value)

      ' Define a string of Fullwidth digits 1-5.
      value = ChrW(&hff11) + ChrW(&hff12) + ChrW(&hff13) + ChrW(&hff14) + ChrW(&hff15)
      ParseDigits(value)

      ' Define a string of Arabic-Indic digits 1-5.
      value = ChrW(&h661) + ChrW(&h662) + ChrW(&h663) + ChrW(&h664) + ChrW(&h665)
      ParseDigits(value)

      ' Define a string of Bengali digits 1-5.
      value = ChrW(&h09e7) + ChrW(&h09e8) + ChrW(&h09e9) + ChrW(&h09ea) + ChrW(&h09eb)
      ParseDigits(value)
   End Sub

   Sub ParseDigits(value As String)
      Try
         Dim number As Integer = Int32.Parse(value)
         Console.WriteLine("'{0}' --> {1}", value, number)
      Catch e As FormatException
         Console.WriteLine("Unable to parse '{0}'.", value)      
      End Try     
   End Sub
End Module
' The example displays the following output:
'       '12345' --> 12345
'       Unable to parse '12345'.
'       Unable to parse '١٢٣٤٥'.
'       Unable to parse '১২৩৪৫'.
using System;

public class Example
{
   public static void Main()
   {
      string value;
      // Define a string of basic Latin digits 1-5.
      value = "\u0031\u0032\u0033\u0034\u0035";
      ParseDigits(value);

      // Define a string of Fullwidth digits 1-5.
      value = "\uFF11\uFF12\uFF13\uFF14\uFF15";
      ParseDigits(value);

      // Define a string of Arabic-Indic digits 1-5.
      value = "\u0661\u0662\u0663\u0664\u0665";
      ParseDigits(value);

      // Define a string of Bengali digits 1-5.
      value = "\u09e7\u09e8\u09e9\u09ea\u09eb";
      ParseDigits(value);
   }

   static void ParseDigits(string value)
   {
      try {
         int number = Int32.Parse(value);
         Console.WriteLine("'{0}' --> {1}", value, number);
      }   
      catch (FormatException) {
         Console.WriteLine("Unable to parse '{0}'.", value);      
      }     
   }
}
// The example displays the following output:
//       '12345' --> 12345
//       Unable to parse '12345'.
//       Unable to parse '١٢٣٤٥'.
//       Unable to parse '১২৩৪৫'.

請參閱

參考

NumberStyles

概念

格式化型別

其他資源

剖析字串

變更記錄

日期

記錄

原因

2010 年 8 月

大規模修訂。

資訊加強。