NumberFormatInfo 類別

定義

提供文化特性特定的格式和剖析數值資訊。Provides culture-specific information for formatting and parsing numeric values.

public ref class NumberFormatInfo sealed : ICloneable, IFormatProvider
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class NumberFormatInfo : ICloneable, IFormatProvider
type NumberFormatInfo = class
    interface ICloneable
    interface IFormatProvider
Public NotInheritable Class NumberFormatInfo
Implements ICloneable, IFormatProvider
繼承
NumberFormatInfo
屬性
實作

範例

下列範例顯示如何NumberFormatInfo抓取對應CultureInfo物件的物件,並使用抓取的物件來查詢特定文化特性的數位格式資訊。The following example shows how to retrieve a NumberFormatInfo object for a corresponding CultureInfo object, and use the retrieved object to query number formatting information for the particular culture.

using namespace System;
using namespace System::Globalization;
using namespace System::Text;

int main()
{
    StringBuilder^ builder = gcnew StringBuilder();

    // Loop through all the specific cultures known to the CLR.
    for each(CultureInfo^ culture in 
        CultureInfo::GetCultures (CultureTypes::SpecificCultures)) 
    {
        // Only show the currency symbols for cultures 
        // that speak English.
        if (culture->TwoLetterISOLanguageName == "en")
        {
            // Display the culture name and currency symbol.
            NumberFormatInfo^ numberFormat = culture->NumberFormat;
            builder->AppendFormat("The currency symbol for '{0}'"+
                "is '{1}'",culture->DisplayName,
                numberFormat->CurrencySymbol);
            builder->AppendLine();
        }
    }
    Console::WriteLine(builder);
}

// This code produces the following output.
//
// The currency symbol for 'English (United States)' is '$'
// The currency symbol for 'English (United Kingdom)' is 'Ј'
// The currency symbol for 'English (Australia)' is '$'
// The currency symbol for 'English (Canada)' is '$'
// The currency symbol for 'English (New Zealand)' is '$'
// The currency symbol for 'English (Ireland)' is '?'
// The currency symbol for 'English (South Africa)' is 'R'
// The currency symbol for 'English (Jamaica)' is 'J$'
// The currency symbol for 'English (Caribbean)' is '$'
// The currency symbol for 'English (Belize)' is 'BZ$'
// The currency symbol for 'English (Trinidad and Tobago)' is 'TT$'
// The currency symbol for 'English (Zimbabwe)' is 'Z$'
// The currency symbol for 'English (Republic of the Philippines)' is 'Php'
using System;
using System.Globalization;
using System.Text;

public sealed class App 
{
    static void Main() 
    {
        StringBuilder sb = new StringBuilder();

        // Loop through all the specific cultures known to the CLR.
        foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) 
        {
            // Only show the currency symbols for cultures that speak English.
            if (ci.TwoLetterISOLanguageName != "en") continue;
             
            // Display the culture name and currency symbol.
            NumberFormatInfo nfi = ci.NumberFormat;
            sb.AppendFormat("The currency symbol for '{0}' is '{1}'",
                ci.DisplayName, nfi.CurrencySymbol);
            sb.AppendLine();
        }
        Console.WriteLine(sb.ToString());
    }
}

// This code produces the following output.
//
// The currency symbol for 'English (United States)' is '$'
// The currency symbol for 'English (United Kingdom)' is '£'
// The currency symbol for 'English (Australia)' is '$'
// The currency symbol for 'English (Canada)' is '$'
// The currency symbol for 'English (New Zealand)' is '$'
// The currency symbol for 'English (Ireland)' is '?'
// The currency symbol for 'English (South Africa)' is 'R'
// The currency symbol for 'English (Jamaica)' is 'J$'
// The currency symbol for 'English (Caribbean)' is '$'
// The currency symbol for 'English (Belize)' is 'BZ$'
// The currency symbol for 'English (Trinidad and Tobago)' is 'TT$'
// The currency symbol for 'English (Zimbabwe)' is 'Z$'
// The currency symbol for 'English (Republic of the Philippines)' is 'Php'
Imports System.Globalization
Imports System.Text

Public Module Example
   Public Sub Main() 
      Dim sb As New StringBuilder()

      ' Loop through all the specific cultures known to the CLR.
      For Each ci In CultureInfo.GetCultures(CultureTypes.SpecificCultures) 
         ' Only show the currency symbols for cultures that speak English.
         If ci.TwoLetterISOLanguageName <> "en" Then Continue For

         ' Display the culture name and currency symbol.
         Dim nfi As NumberFormatInfo = ci.NumberFormat
         sb.AppendFormat("The currency symbol for '{0}' is '{1}'",
                         ci.DisplayName, nfi.CurrencySymbol)
         sb.AppendLine()
      Next
      Console.WriteLine(sb.ToString())
   End Sub
End Module
' The example displays output like the following:
'       The currency symbol for 'English (United States)' is '$'
'       The currency symbol for 'English (United Kingdom)' is '£'
'       The currency symbol for 'English (Australia)' is '$'
'       The currency symbol for 'English (Canada)' is '$'
'       The currency symbol for 'English (New Zealand)' is '$'
'       The currency symbol for 'English (Ireland)' is '?'
'       The currency symbol for 'English (South Africa)' is 'R'
'       The currency symbol for 'English (Jamaica)' is 'J$'
'       The currency symbol for 'English (Caribbean)' is '$'
'       The currency symbol for 'English (Belize)' is 'BZ$'
'       The currency symbol for 'English (Trinidad and Tobago)' is 'TT$'
'       The currency symbol for 'English (Zimbabwe)' is 'Z$'
'       The currency symbol for 'English (Republic of the Philippines)' is 'Php'
'       The currency symbol for 'English (India)' is 'Rs.'
'       The currency symbol for 'English (Malaysia)' is 'RM'
'       The currency symbol for 'English (Singapore)' is '$'

備註

NumberFormatInfo類別包含特定文化特性的資訊,可在您格式化和剖析數值時使用。The NumberFormatInfo class contains culture-specific information that is used when you format and parse numeric values. 此資訊包含貨幣符號、十進位符號、群組分隔符號符號,以及正和負號的符號。This information includes the currency symbol, the decimal symbol, the group separator symbol, and the symbols for positive and negative signs.

具現化 NumberFormatInfo 物件Instantiating a NumberFormatInfo object

您可以具現NumberFormatInfo化物件,代表目前文化特性的格式化慣例、不因文化特性而異、特定文化特性或中性文化特性。You can instantiate a NumberFormatInfo object that represents the formatting conventions of the current culture, the invariant culture, a specific culture, or a neutral culture.

將目前文化特性的 NumberFormatInfo 物件具現化Instantiating a NumberFormatInfo object for the current culture

您可以使用下列NumberFormatInfo任一方式,將目前線程文化特性的物件具現化。You can instantiate a NumberFormatInfo object for the current thread culture in any of the following ways. 在每個案例中, NumberFormatInfo傳回的物件都是唯讀的。In each case, the returned NumberFormatInfo object is read-only.

下列範例會使用這三種方式來NumberFormatInfo建立物件,以代表目前文化特性的格式化慣例。The following example uses these three ways to create NumberFormatInfo objects that represent the formatting conventions of the current culture. 它也會抓取IsReadOnly屬性的值,以說明每個物件都是唯讀的。It also retrieves the value of the IsReadOnly property to illustrate that each object is read-only.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      NumberFormatInfo current1 = CultureInfo.CurrentCulture.NumberFormat;
      Console.WriteLine(current1.IsReadOnly);
      
      NumberFormatInfo current2 = NumberFormatInfo.CurrentInfo;
      Console.WriteLine(current2.IsReadOnly);
      
      NumberFormatInfo current3 = NumberFormatInfo.GetInstance(CultureInfo.CurrentCulture);
      Console.WriteLine(current3.IsReadOnly);
   }
}
// The example displays the following output:
//       True
//       True
//       True
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim current1 As NumberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
      Console.WriteLine(current1.IsReadOnly)
      
      Dim current2 As NumberFormatInfo = NumberFormatInfo.CurrentInfo
      Console.WriteLine(current2.IsReadOnly)
      
      Dim current3 As NumberFormatInfo = NumberFormatInfo.GetInstance(CultureInfo.CurrentCulture)
      Console.WriteLine(current3.IsReadOnly)
   End Sub
End Module
' The example displays the following output:
'       True
'       True
'       True

您可以使用下列任何NumberFormatInfo方式來建立可寫入的物件,以代表目前線程文化特性的慣例:You can create a writable NumberFormatInfo object that represents the conventions of the current thread culture in any of the following ways:

下列範例說明這兩種具現化NumberFormatInfo物件的方法,並顯示其IsReadOnly屬性的值,以說明該物件不是唯讀的。The following example illustrates these two ways of instantiating a NumberFormatInfo object, and displays the value of its IsReadOnly property to illustrate that the object is not read-only.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      NumberFormatInfo current1 = NumberFormatInfo.CurrentInfo;
      current1 = (NumberFormatInfo) current1.Clone();
      Console.WriteLine(current1.IsReadOnly);

      CultureInfo culture2 = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
      NumberFormatInfo current2 = culture2.NumberFormat;
      Console.WriteLine(current2.IsReadOnly);
   }
}
// The example displays the following output:
//       False
//       False
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim current1 As NumberFormatInfo = NumberFormatInfo.CurrentInfo
      current1 = CType(current1.Clone(), NumberFormatInfo)
      Console.WriteLine(current1.IsReadOnly)

      Dim culture2 As CultureInfo = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name)
      Dim current2 As NumberFormatInfo = culture2.NumberFormat
      Console.WriteLine(current2.IsReadOnly)
   End Sub
End Module
' The example displays the following output:
'       False
'       False

請注意,Windows 作業系統可讓使用者透過 [控制台] 中的NumberFormatInfo [區域] 和 [語言] 專案,覆寫數位格式和剖析作業中使用的某些屬性值。Note that the Windows operating system allows the user to override some of the NumberFormatInfo property values used in numeric formatting and parsing operations through the Region and Language item in Control Panel. 例如,其文化特性為英文(美國)的使用者可能會選擇將貨幣值顯示為1.1 美元,而不是預設的 $1.1。For example, a user whose culture is English (United States) might choose to display currency values as 1.1 USD instead of the default of $1.1. NumberFormatInfo先前討論的方式取得的物件會反映這些使用者覆寫。The NumberFormatInfo objects retrieved in the ways discussed previously all reflect these user overrides. 如果不想要這樣做,您可以NumberFormatInfo藉由CultureInfo.CultureInfo(String, Boolean)呼叫函式false並提供的值給,來建立不會反映使用者覆寫的物件(也就是讀取/寫入,而不是useUserOverride唯讀)。引數.If this is undesirable, you can create a NumberFormatInfo object that does not reflect user overrides (and that is also read/write rather than read-only) by calling the CultureInfo.CultureInfo(String, Boolean) constructor and supplying a value of false for the useUserOverride argument. 下列範例會針對目前文化特性是英文(美國)且其貨幣符號已從 $ 到美元的預設值變更的系統提供圖例。The following example provides an illustration for a system whose current culture is English (United States) and whose currency symbol has been changed from the default of $ to USD.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      CultureInfo culture;
      NumberFormatInfo nfi;
      
      culture = CultureInfo.CurrentCulture;
      nfi = culture.NumberFormat;
      Console.WriteLine("Culture Name:    {0}", culture.Name);
      Console.WriteLine("User Overrides:  {0}", culture.UseUserOverride);
      Console.WriteLine("Currency Symbol: {0}\n", culture.NumberFormat.CurrencySymbol);
            
      culture = new CultureInfo(CultureInfo.CurrentCulture.Name, false);
      Console.WriteLine("Culture Name:    {0}", culture.Name);
      Console.WriteLine("User Overrides:  {0}", culture.UseUserOverride);
      Console.WriteLine("Currency Symbol: {0}", culture.NumberFormat.CurrencySymbol);
   }
}
// The example displays the following output:
//       Culture Name:    en-US
//       User Overrides:  True
//       Currency Symbol: USD
//       
//       Culture Name:    en-US
//       User Overrides:  False
//       Currency Symbol: $
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim culture As CultureInfo
      Dim nfi As NumberFormatInfo
      
      culture = CultureInfo.CurrentCulture
      nfi = culture.NumberFormat
      Console.WriteLine("Culture Name:    {0}", culture.Name)
      Console.WriteLine("User Overrides:  {0}", culture.UseUserOverride)
      Console.WriteLine("Currency Symbol: {0}", culture.NumberFormat.CurrencySymbol)
      Console.WriteLine()
            
      culture = New CultureInfo(CultureInfo.CurrentCulture.Name, False)
      Console.WriteLine("Culture Name:    {0}", culture.Name)
      Console.WriteLine("User Overrides:  {0}", culture.UseUserOverride)
      Console.WriteLine("Currency Symbol: {0}", culture.NumberFormat.CurrencySymbol)
   End Sub
End Module
' The example displays the following output:
'       Culture Name:    en-US
'       User Overrides:  True
'       Currency Symbol: USD
'       
'       Culture Name:    en-US
'       User Overrides:  False
'       Currency Symbol: $

true CultureInfo.DateTimeFormat CultureInfo.NumberFormat如果屬性設定為,則也會從使用者設定中抓取屬性、和CultureInfo.TextInfoCultureInfo.UseUserOverrideIf the CultureInfo.UseUserOverride property is set to true, the properties CultureInfo.DateTimeFormat, CultureInfo.NumberFormat, and CultureInfo.TextInfo are also retrieved from the user settings. 如果使用者設定與CultureInfo物件相關聯的文化OptionalCalendars特性不相容(例如,如果選取的行事曆不是由屬性所列出的其中一個行事曆),則方法的結果和屬性的值會是useraccountcontrol.If the user settings are incompatible with the culture associated with the CultureInfo object (for example, if the selected calendar is not one of the calendars listed by the OptionalCalendars property), the results of the methods and the values of the properties are undefined.

具現化不因文化特性而異的 NumberFormatInfo 物件Instantiating a NumberFormatInfo object for the invariant culture

不因文化特性而異,表示不區分文化特性的文化特性。The invariant culture represents a culture that is culture-insensitive. 它是以英文語言為基礎,而不是在任何特定的英文國家/地區。It is based on the English language but not on any specific English-speaking country/region. 雖然特定文化特性的資料可以是動態的,而且可以變更以反映新的文化慣例或使用者喜好設定,但不變文化特性的資料並不會變更。Although the data of specific cultures can be dynamic and can change to reflect new cultural conventions or user preferences, the data of the invariant culture does not change. 表示不因文化特性而異的格式設定慣例的物件,可用於格式化作業,其中的結果字串不應該因文化特性而有所不同。NumberFormatInfoA NumberFormatInfo object that represents the formatting conventions of the invariant culture can be used for formatting operations in which result strings should not vary by culture.

您可以使用下列NumberFormatInfo方式,將代表不因文化特性之格式設定慣例的物件具現化:You can instantiate a NumberFormatInfo object that represents the formatting conventions of the invariant culture in the following ways:

下列範例會使用這些方法來具現化NumberFormatInfo代表不因文化特性而異的物件。The following example uses each of these methods to instantiate a NumberFormatInfo object that represents the invariant culture. 然後,它會指出物件是否為唯讀,It then indicates whether the object is read-only,

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      NumberFormatInfo nfi;
      
      nfi = System.Globalization.NumberFormatInfo.InvariantInfo;
      Console.WriteLine(nfi.IsReadOnly);               
      
      nfi = CultureInfo.InvariantCulture.NumberFormat;
      Console.WriteLine(nfi.IsReadOnly);               
      
      nfi = New NumberFormatInfo();
      Console.WriteLine(nfi.IsReadOnly);               
   }
}
// The example displays the following output:
//       True
//       True
//       False
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim nfi As NumberFormatInfo
      
      nfi = System.Globalization.NumberFormatInfo.InvariantInfo
      Console.WriteLine(nfi.IsReadOnly)               
      
      nfi = CultureInfo.InvariantCulture.NumberFormat
      Console.WriteLine(nfi.IsReadOnly)               
      
      nfi = New NumberFormatInfo()
      Console.WriteLine(nfi.IsReadOnly)               
   End Sub
End Module
' The example displays the following output:
'       True
'       True
'       False

具現化特定文化特性的 NumberFormatInfo 物件Instantiating a NumberFormatInfo object for a specific culture

特定的文化特性代表特定國家/地區中所說的語言。A specific culture represents a language that is spoken in a particular country/region. 例如,en-us 是特定文化特性,代表美國所說的英文語言,而 en-us 則是特定文化特性,代表加拿大所說的英文語言。For example, en-US is a specific culture that represents the English language spoken in the United States, and en-CA is a specific culture that represents the English language spoken in Canada. 您可以使用下列NumberFormatInfo方式,將代表特定文化特性之格式化慣例的物件具現化:You can instantiate a NumberFormatInfo object that represents the formatting conventions of a specific culture in the following ways:

下列範例會使用這四種方式來建立NumberFormatInfo物件,以反映印尼文(印尼)文化特性的格式化慣例。The following example uses these four ways to create a NumberFormatInfo object that reflects the formatting conventions of the Indonesian (Indonesia) culture. 它也會指出每個物件是否為唯讀。It also indicates whether each object is read-only.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      CultureInfo culture;
      NumberFormatInfo nfi;
      
      nfi = CultureInfo.GetCultureInfo("id-ID").NumberFormat;
      Console.WriteLine("Read-only: {0}", nfi.IsReadOnly);
      
      culture = new CultureInfo("id-ID");
      nfi = NumberFormatInfo.GetInstance(culture);
      Console.WriteLine("Read-only: {0}", nfi.IsReadOnly);
      
      culture = CultureInfo.CreateSpecificCulture("id-ID");
      nfi = culture.NumberFormat;
      Console.WriteLine("Read-only: {0}", nfi.IsReadOnly);
      
      culture = new CultureInfo("id-ID");
      nfi = culture.NumberFormat;
      Console.WriteLine("Read-only: {0}", nfi.IsReadOnly);
   }
}
// The example displays the following output:
//       Read-only: True
//       Read-only: False
//       Read-only: False
//       Read-only: False
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim culture As CultureInfo
      Dim nfi As NumberFormatInfo
      
      nfi = CultureInfo.GetCultureInfo("id-ID").NumberFormat
      Console.WriteLine("Read-only: {0}", nfi.IsReadOnly)
      
      culture = New CultureInfo("id-ID")
      nfi = NumberFormatInfo.GetInstance(culture)
      Console.WriteLine("Read-only: {0}", nfi.IsReadOnly)
      
      culture = CultureInfo.CreateSpecificCulture("id-ID")
      nfi = culture.NumberFormat
      Console.WriteLine("Read-only: {0}", nfi.IsReadOnly)
      
      culture = New CultureInfo("id-ID")
      nfi = culture.NumberFormat
      Console.WriteLine("Read-only: {0}", nfi.IsReadOnly)
   End Sub
End Module
' The example displays the following output:
'       Read-only: True
'       Read-only: False
'       Read-only: False
'       Read-only: False

為中性文化特性具現化 NumberFormatInfo 物件Instantiating a NumberFormatInfo object for a neutral culture

中性文化特性代表與國家/地區無關的文化特性或語言。A neutral culture represents a culture or language that is independent of a country/region. 它通常是一或多個特定文化特性的父系。It is typically the parent of one or more specific cultures. 例如,fr 是法文語言的中性文化特性,以及 fr-fr 文化特性的父系。For example, fr is a neutral culture for the French language and the parent of the fr-FR culture. 您可以建立NumberFormatInfo物件來表示中性文化特性的格式設定慣例,其方式與NumberFormatInfo建立代表特定文化特性之格式化慣例的物件相同。You create a NumberFormatInfo object that represents the formatting conventions of a neutral culture in the same way that you create a NumberFormatInfo object that represents the formatting conventions of a specific culture.

注意

在和較舊版本中,嘗試NumberFormatInfo取出反映中性文化NotSupportedException特性之格式化慣例的物件會擲回例外狀況。 .NET Framework 3.5.NET Framework 3.5In the .NET Framework 3.5.NET Framework 3.5 and earlier versions, trying to retrieve a NumberFormatInfo object that reflects the formatting conventions of a neutral culture throws a NotSupportedException exception.

不過,因為它與特定國家/地區無關,中性文化特性則缺少特定文化特性格式資訊。However, because it is independent of a specific country/region, a neutral culture lacks culture-specific formatting information. .NET Framework 會傳回一個NumberFormatInfo物件,它會反映特定文化特性的格式設定慣例,這是中性文化特性的子系,而不是以泛型值填入物件。NumberFormatInfoRather than populating the NumberFormatInfo object with generic values, the .NET Framework returns a NumberFormatInfo object that reflects the formatting conventions of a specific culture that is a child of the neutral culture. 例如, NumberFormatInfo中性 en 文化特性的物件會反映 en-us 文化特性的格式設定慣例, NumberFormatInfo而 fr 文化特性的物件會反映 fr-fr 文化特性的格式設定慣例。For example, the NumberFormatInfo object for the neutral en culture reflects the formatting conventions of the en-US culture, and the NumberFormatInfo object for the fr culture reflects the formatting conventions of the fr-FR culture.

您可以使用如下所示的程式碼,來判斷每個中性文化特性所代表的特定文化特性格式慣例。You can use code like the following to determine which specific culture's formatting conventions each neutral culture represents.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;

public class Example
{
   public static void Main()
   {
      // Get all the neutral cultures
      List<String> names = new List<String>();
      Array.ForEach(CultureInfo.GetCultures(CultureTypes.NeutralCultures),
                    culture => names.Add(culture.Name));
      names.Sort();
      foreach (var name in names) {
         // Ignore the invariant culture.
         if (name == "") continue;
         
         ListSimilarChildCultures(name);        
      }
   }

   private static void ListSimilarChildCultures(string name)
   { 
      // Create the neutral NumberFormatInfo object.
      NumberFormatInfo nfi = CultureInfo.GetCultureInfo(name).NumberFormat;
      // Retrieve all specific cultures of the neutral culture.
      CultureInfo[] cultures = Array.FindAll(CultureInfo.GetCultures(CultureTypes.SpecificCultures), 
                               culture => culture.Name.StartsWith(name + "-", StringComparison.OrdinalIgnoreCase));
      // Create an array of NumberFormatInfo properties
      PropertyInfo[] properties = typeof(NumberFormatInfo).GetProperties(BindingFlags.Instance | BindingFlags.Public);
      bool hasOneMatch = false;

      foreach (var ci in cultures) {
         bool match = true;     
         // Get the NumberFormatInfo for a specific culture.
         NumberFormatInfo specificNfi = ci.NumberFormat;
         // Compare the property values of the two.
         foreach (var prop in properties) {
            // We're not interested in the value of IsReadOnly.     
            if (prop.Name == "IsReadOnly") continue;
            
            // For arrays, iterate the individual elements to see if they are the same.
            if (prop.PropertyType.IsArray) { 
               IList nList = (IList) prop.GetValue(nfi, null);
               IList sList = (IList) prop.GetValue(specificNfi, null);
               if (nList.Count != sList.Count) {
                  match = false;
                  break;
               } 

               for (int ctr = 0; ctr < nList.Count; ctr++) {
                  if (! nList[ctr].Equals(sList[ctr])) {
                     match = false;
                     break;
                  }     
               }
            }   
            else if (! prop.GetValue(specificNfi).Equals(prop.GetValue(nfi))) {
               match = false;
               break;   
            }        
         }
         if (match) {
            Console.WriteLine("NumberFormatInfo object for '{0}' matches '{1}'", 
                                      name, ci.Name);
            hasOneMatch = true;
         }                                       
      }
      if (! hasOneMatch)
         Console.WriteLine("NumberFormatInfo object for '{0}' --> No Match", name);            

      Console.WriteLine();
   }
}
Imports System.Collections
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Reflection

Module Example
   Public Sub Main()
      ' Get all the neutral cultures
      Dim names As New List(Of String)
      Array.ForEach(CultureInfo.GetCultures(CultureTypes.NeutralCultures),
                    Sub(culture) names.Add(culture.Name))
      names.Sort()
      For Each name In names
         ' Ignore the invariant culture.
         If name = "" Then Continue For
         
         ListSimilarChildCultures(name)        
      Next
   End Sub

   Private Sub ListSimilarChildCultures(name As String)
      ' Create the neutral NumberFormatInfo object.
      Dim nfi As NumberFormatInfo = CultureInfo.GetCultureInfo(name).NumberFormat
      ' Retrieve all specific cultures of the neutral culture.
      Dim cultures() As CultureInfo = Array.FindAll(CultureInfo.GetCultures(CultureTypes.SpecificCultures), 
                               Function(culture) culture.Name.StartsWith(name + "-", StringComparison.OrdinalIgnoreCase))
      ' Create an array of NumberFormatInfo properties
      Dim properties() As PropertyInfo = GetType(NumberFormatInfo).GetProperties(BindingFlags.Instance Or BindingFlags.Public)
      Dim hasOneMatch As Boolean = False

      For Each ci In cultures
         Dim match As Boolean = True     
         ' Get the NumberFormatInfo for a specific culture.
         Dim specificNfi As NumberFormatInfo = ci.NumberFormat
         ' Compare the property values of the two.
         For Each prop In properties
            ' We're not interested in the value of IsReadOnly.     
            If prop.Name = "IsReadOnly" Then Continue For
            
            ' For arrays, iterate the individual elements to see if they are the same.
            If prop.PropertyType.IsArray Then 
               Dim nList As IList = CType(prop.GetValue(nfi, Nothing), IList)
               Dim sList As IList = CType(prop.GetValue(specificNfi, Nothing), IList)
               If nList.Count <> sList.Count Then
                  match = false
                  Exit For
               End If 

               For ctr As Integer = 0 To nList.Count - 1
                  If Not nList(ctr).Equals(sList(ctr)) 
                     match = false
                     Exit For
                  End If     
               Next
            Else If Not prop.GetValue(specificNfi).Equals(prop.GetValue(nfi))
               match = false
               Exit For   
            End If        
         Next
         If match Then
            Console.WriteLine("NumberFormatInfo object for '{0}' matches '{1}'", 
                                      name, ci.Name)
            hasOneMatch = true
         End If                                       
      Next
      If Not hasOneMatch Then
         Console.WriteLine("NumberFormatInfo object for '{0}' --> No Match", name)            
      End If
      
      Console.WriteLine()
   End Sub
End Module

NumberFormatInfo 和動態資料NumberFormatInfo and dynamic data

NumberFormatInfo來格式化類別所提供之數值的文化特性(culture)特定資料是動態的,就像CultureInfo類別所提供的文化特性資料一樣。The culture-specific data for formatting numeric values provided by the NumberFormatInfo class is dynamic, just like the cultural data provided by the CultureInfo class. 對於NumberFormatInfo與特定CultureInfo物件相關聯之物件的值,您不應該進行任何的假設。You should not make any assumptions about the stability of values for NumberFormatInfo objects that are associated with particular CultureInfo objects. 只有不因文化特性而異的資料與其相關NumberFormatInfo聯的物件,才是穩定的。Only the data provided by the invariant culture and its associated NumberFormatInfo object is stable. 其他資料可能會在應用程式會話之間變更,甚至是在單一會話內,因為下列原因:Other data can change between application sessions, or even within a single session, for the following reasons:

  • 系統更新。System updates. 文化特性喜好設定(例如貨幣符號或貨幣格式)會隨著時間而改變。Cultural preferences such as the currency symbol or currency formats change over time. 發生這種情況時,Windows Update 包含特定NumberFormatInfo文化特性之屬性值的變更。When this happens, Windows Update includes changes to the NumberFormatInfo property value for a particular culture.

  • 取代文化特性。Replacement cultures. CultureAndRegionInfoBuilder類別可以用來取代現有文化特性的資料。The CultureAndRegionInfoBuilder class can be used to replace the data of an existing culture.

  • 屬性值的串聯變更。Cascading changes to property values. 許多與文化特性相關的屬性可能會在執行時間變更,而這會導致NumberFormatInfo資料變更。A number of culture-related properties can change at run time, which, in turn, causes NumberFormatInfo data to change. 例如,您可以用程式設計方式或透過使用者動作來變更目前的文化特性。For example, the current culture can be changed either programmatically or through user action. 發生這種情況時NumberFormatInfoCurrentInfo屬性傳回的物件會變更為與目前文化特性相關聯的物件。When this happens, the NumberFormatInfo object returned by the CurrentInfo property changes to an object associated with the current culture.

  • 使用者喜好設定。User preferences. 您的應用程式使用者可能會透過 [控制台] 中的 [地區和語言選項],覆寫與目前系統文化特性相關聯的一些值。Users of your application might override some of the values associated with the current system culture through the region and language options in Control Panel. 例如,使用者可能會選擇不同的貨幣符號或不同的十進位分隔符號。For example, users might choose a different currency symbol or a different decimal separator symbol. 如果屬性設定為true (其預設值) NumberFormatInfo ,則也會從使用者設定中抓取物件的屬性。 CultureInfo.UseUserOverrideIf the CultureInfo.UseUserOverride property is set to true (its default value), the properties of the NumberFormatInfo object are also retrieved from the user settings.

從 .NET Framework 2.0 開始, NumberFormatInfo物件的所有使用者可覆寫屬性會在物件建立時初始化。Starting with the .NET Framework 2.0, all user-overridable properties of a NumberFormatInfo object are initialized when the object is created. 仍然有可能會造成不一致的情況,因為物件建立或使用者覆寫程式都不是不可部分完成的,而且相關的值可能會在物件建立期間變更。There is still a possibility of inconsistency, because neither object creation nor the user override process is atomic, and the relevant values may change during object creation. 不過,這些不一致的情況應該非常罕見。However, these inconsistencies should be extremely rare.

您可以控制是否要在代表與目前NumberFormatInfo執行緒文化特性相同文化特性的物件中反映使用者覆寫。You can control whether user overrides are reflected in NumberFormatInfo objects that represent the same culture as the current thread culture. 下表列出NumberFormatInfo物件的抓取方式,並指出產生的物件是否會反映使用者覆寫。The following table lists the ways in which a NumberFormatInfo object can be retrieved and indicates whether the resulting object reflects user overrides.

CultureInfo 和 NumberFormatInfo 物件的來源Source of CultureInfo and NumberFormatInfo object 反映使用者覆寫Reflects user overrides
CultureInfo.CurrentCulture.NumberFormat 屬性CultureInfo.CurrentCulture.NumberFormat property Yes
NumberFormatInfo.CurrentInfo 屬性NumberFormatInfo.CurrentInfo property [是]Yes
CultureInfo.CreateSpecificCulture 方法CultureInfo.CreateSpecificCulture method Yes
CultureInfo.GetCultureInfo 方法CultureInfo.GetCultureInfo method No
CultureInfo(String) 建構函式CultureInfo(String) constructor Yes
CultureInfo.CultureInfo(String, Boolean) 建構函式CultureInfo.CultureInfo(String, Boolean) constructor 取決於參數的useUserOverrideDepends on value of useUserOverride parameter

除非有合理的理由要這麼做,否則當您在用戶端應用程式中使用NumberFormatInfo物件來格式化和剖析使用者輸入或顯示數值資料時,您應該尊重使用者覆寫。Unless there is a compelling reason to do otherwise, you should respect user overrides when you use the NumberFormatInfo object in client applications to format and parse user input or to display numeric data. 對於伺服器應用程式或自動應用程式,您不應該尊重使用者覆寫。For server applications or unattended applications, you should not respect user overrides. 不過,如果您以明確或NumberFormatInfo隱含方式使用物件,以字串形式保存數值資料,您應該NumberFormatInfo使用反映不因文化特性而異的格式設定慣例的物件,或者您應該指定您使用的自訂數值格式字串,無論文化特性為何。However, if you are using the NumberFormatInfo object either explicitly or implicitly to persist numeric data in string form, you should either use a NumberFormatInfo object that reflects the formatting conventions of the invariant culture, or you should specify a custom numeric format string that you use regardless of culture.

IFormatProvider、NumberFormatInfo 和數位格式IFormatProvider, NumberFormatInfo, and numeric formatting

在所有數值格式化作業中,會隱含或明確使用物件。NumberFormatInfoA NumberFormatInfo object is used implicitly or explicitly in all numeric formatting operations. 這些包括呼叫下列方法:These include calls to the following methods:

所有數值格式化作業都會使用實作為IFormatProviderAll numeric formatting operations make use of an IFormatProvider implementation. 介面包含單一GetFormat(Type)方法。 IFormatProviderThe IFormatProvider interface includes a single method, GetFormat(Type). 這是一種回呼方法,會傳遞Type代表提供格式資訊所需類型的物件。This is a callback method that is passed a Type object that represents the type needed to provide formatting information. 方法會負責傳回該類型的實例,或者null,如果無法提供類型的實例,則傳回。The method is responsible for returning either an instance of that type or null, if it cannot provide an instance of the type. .NET Framework 提供格式化數位IFormatProvider的兩個方式:The .NET Framework provides two IFormatProvider implementations for formatting numbers:

如果未將CultureInfo CultureInfo.CurrentCulture實作為明確提供給格式化方法,則會使用代表目前線程文化特性之屬性所傳回的物件。 IFormatProviderIf an IFormatProvider implementation is not provided to a formatting method explicitly, a CultureInfo object returned by the CultureInfo.CurrentCulture property that represents the current thread culture is used.

下列範例說明如何定義自訂IFormatProvider IFormatProvider的執行,以NumberFormatInfo格式化作業中的介面和類別之間的關聯性。The following example illustrates the relationship between the IFormatProvider interface and the NumberFormatInfo class in formatting operations by defining a custom IFormatProvider implementation. GetFormat方法會顯示格式化作業所要求之物件的型別名稱。Its GetFormat method displays the type name of the object requested by the formatting operation. 如果介面要求NumberFormatInfo物件,這個方法會NumberFormatInfo提供目前線程文化特性的物件。If the interface is requesting a NumberFormatInfo object, this method provides the NumberFormatInfo object for the current thread culture. 如範例的Decimal.ToString(IFormatProvider)輸出所示,方法會NumberFormatInfo要求物件提供String.Format(IFormatProvider, String, Object[])格式資訊NumberFormatInfo ,而ICustomFormatter方法會要求和DateTimeFormatInfo物件以及實作.As the output from the example shows, the Decimal.ToString(IFormatProvider) method requests a NumberFormatInfo object to provide formatting information, whereas the String.Format(IFormatProvider, String, Object[]) method requests NumberFormatInfo and DateTimeFormatInfo objects as well as an ICustomFormatter implementation.

using System;
using System.Globalization;

public class CurrentCultureFormatProvider : IFormatProvider
{
   public Object GetFormat(Type formatType) 
   {
      Console.WriteLine("Requesting an object of type {0}", 
                        formatType.Name);
      if (formatType == typeof(NumberFormatInfo))
         return NumberFormatInfo.CurrentInfo;
      else if (formatType == typeof(DateTimeFormatInfo))
         return DateTimeFormatInfo.CurrentInfo;
      else
         return null;
   }
}

public class Example
{
   public static void Main()
   {
      Decimal amount = 1203.541m;
      string value = amount.ToString("C2", new CurrentCultureFormatProvider());
      Console.WriteLine(value);
      Console.WriteLine();
      string composite = String.Format(new CurrentCultureFormatProvider(), 
                                       "Date: {0}   Amount: {1}   Description: {2}",
                                       DateTime.Now, 1264.03m, "Service Charge");
      Console.WriteLine(composite);
      Console.WriteLine();
   }
}
// The example displays output like the following:
//    Requesting an object of type NumberFormatInfo
//    $1,203.54
//    
//    Requesting an object of type ICustomFormatter
//    Requesting an object of type DateTimeFormatInfo
//    Requesting an object of type NumberFormatInfo
//    Date: 11/15/2012 2:00:01 PM   Amount: 1264.03   Description: Service Charge
Imports System.Globalization

Public Class CurrentCultureFormatProvider : Implements IFormatProvider
   Public Function GetFormat(formatType As Type) As Object _
                   Implements IFormatProvider.GetFormat
      Console.WriteLine("Requesting an object of type {0}", 
                        formatType.Name)
      If formatType Is GetType(NumberFormatInfo) Then
         Return NumberFormatInfo.CurrentInfo
      Else If formatType Is GetType(DateTimeFormatInfo) Then
         Return DateTimeFormatInfo.CurrentInfo
      Else
         Return Nothing
      End If
   End Function
End Class

Module Example
   Public Sub Main()
      Dim amount As Decimal = 1203.541d
      Dim value As String = amount.ToString("C2", New CurrentCultureFormatProvider())
      Console.WriteLine(value)
      Console.WriteLine()
      Dim composite As String = String.Format(New CurrentCultureFormatProvider, 
                                              "Date: {0}   Amount: {1}   Description: {2}",
                                              Date.Now, 1264.03d, "Service Charge")
      Console.WriteLine(composite)
      Console.WriteLine()
   End Sub
End Module
' The example displays output like the following:
'    Requesting an object of type NumberFormatInfo
'    $1,203.54
'    
'    Requesting an object of type ICustomFormatter
'    Requesting an object of type DateTimeFormatInfo
'    Requesting an object of type NumberFormatInfo
'    Date: 11/15/2012 2:00:01 PM   Amount: 1264.03   Description: Service Charge

如果未在數值格式化方法呼叫中明確提供CultureInfo.CurrentCulture.GetFormat NumberFormatInfo 實值,方法會呼叫方法,以傳回對應至目前線程文化IFormatProvider特性的物件。If an IFormatProvider implementation is not explicitly provided in a numeric formatting method call, the method calls the CultureInfo.CurrentCulture.GetFormat method, which returns the NumberFormatInfo object that corresponds to the current thread culture.

格式字串和 NumberFormatInfo 屬性Format strings and NumberFormatInfo properties

每個格式化作業都使用標準或自訂數值格式字串,從數位產生結果字串。Every formatting operation uses either a standard or a custom numeric format string to produce a result string from a number. 在某些情況下,使用格式字串來產生結果字串是明確的,如下列範例所示。In some cases, the use of a format string to produce a result string is explicit, as in the following example. 這個程式碼會Decimal.ToString(IFormatProvider)呼叫方法,使用Decimal en-us 文化特性的格式化慣例,將值轉換成數個不同的字串表示。This code calls the Decimal.ToString(IFormatProvider) method to convert a Decimal value to a number of different string representations by using the formatting conventions of the en-US culture.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] formatStrings = { "C2", "E1", "F", "G3", "N", 
                                 "#,##0.000", "0,000,000,000.0##" };
      CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
      Decimal[] values = { 1345.6538m, 1921651.16m };
      
      foreach (var value in values) {
         foreach (var formatString in formatStrings) {
            string resultString = value.ToString(formatString, culture);
            Console.WriteLine("{0,-18} -->  {1}", formatString, resultString);
         }
         Console.WriteLine();      
      }   
   }
}
// The example displays the following output:
//       C2                 -->  $1,345.65
//       E1                 -->  1.3E+003
//       F                  -->  1345.65
//       G3                 -->  1.35E+03
//       N                  -->  1,345.65
//       #,##0.000          -->  1,345.654
//       0,000,000,000.0##  -->  0,000,001,345.654
//       
//       C2                 -->  $1,921,651.16
//       E1                 -->  1.9E+006
//       F                  -->  1921651.16
//       G3                 -->  1.92E+06
//       N                  -->  1,921,651.16
//       #,##0.000          -->  1,921,651.160
//       0,000,000,000.0##  -->  0,001,921,651.16
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim formatStrings() As String = { "C2", "E1", "F", "G3", "N", 
                                        "#,##0.000", "0,000,000,000.0##" }
      Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture("en-US")
      Dim values() As Decimal = { 1345.6538d, 1921651.16d }
      
      For Each value In values
         For Each formatString In formatStrings
            Dim resultString As String = value.ToString(formatString, culture)
            Console.WriteLine("{0,-18} -->  {1}", formatString, resultString)
         Next
         Console.WriteLine()      
      Next   
   End Sub
End Module
' The example displays the following output:
'       C2                 -->  $1,345.65
'       E1                 -->  1.3E+003
'       F                  -->  1345.65
'       G3                 -->  1.35E+03
'       N                  -->  1,345.65
'       #,##0.000          -->  1,345.654
'       0,000,000,000.0##  -->  0,000,001,345.654
'       
'       C2                 -->  $1,921,651.16
'       E1                 -->  1.9E+006
'       F                  -->  1921651.16
'       G3                 -->  1.92E+06
'       N                  -->  1,921,651.16
'       #,##0.000          -->  1,921,651.160
'       0,000,000,000.0##  -->  0,001,921,651.16

在其他情況下,使用格式字串是隱含的。In other cases, the use of a format string is implicit. 例如,在下列方法中呼叫預設或無參數Decimal.ToString()方法時,會使用一般("G")格式規範和目前文化特性的慣例來格式化Decimal實例的值,在此案例中為en-us 文化特性。For example, in the following method calls to the default or parameterless Decimal.ToString() method, the value of the Decimal instance is formatted by using the general ("G") format specifier and the conventions of the current culture, which in this case is the en-US culture.

using System;

public class Example
{
   public static void Main()
   {
      Decimal[] values = { 1345.6538m, 1921651.16m };
      
      foreach (var value in values) {
         string resultString = value.ToString();
         Console.WriteLine(resultString);
         Console.WriteLine();      
      }   
   }
}
// The example displays the following output:
//       1345.6538
//       
//       1921651.16
Module Example
   Public Sub Main()
      Dim values() As Decimal = { 1345.6538d, 1921651.16d }
      
      For Each value In values
         Dim resultString As String = value.ToString()
         Console.WriteLine(resultString)
         Console.WriteLine()      
      Next   
   End Sub
End Module
' The example displays the following output:
'       1345.6538
'       
'       1921651.16

每個標準數值格式字串會使用一NumberFormatInfo或多個屬性來決定結果字串中所使用的模式或符號。Each standard numeric format string uses one or more NumberFormatInfo properties to determine the pattern or the symbols used in the result string. 同樣地,「0」和「#」以外的每個自訂數值格式規範都會在NumberFormatInfo屬性所定義的結果字串中插入符號。Similarly, each custom numeric format specifier except "0" and "#" insert symbols in the result string that are defined by NumberFormatInfo properties. 下表列出標準和自訂數值格式規範及其相關聯NumberFormatInfo的屬性。The following table lists the standard and custom numeric format specifiers and their associated NumberFormatInfo properties. 若要變更特定文化特性的結果字串外觀,請參閱修改 NumberFormatInfo 屬性一節。To change the appearance of the result string for a particular culture, see the Modifying NumberFormatInfo properties section. 如需有關使用這些格式規範的詳細資訊,請參閱標準數值格式字串自訂數值格式字串For details about the use of these format specifiers, see Standard Numeric Format Strings and Custom Numeric Format Strings.

格式規範Format specifier 相關聯的屬性Associated properties
"C" 或 "c" (貨幣格式規範)"C" or "c" (currency format specifier) CurrencyDecimalDigits,用來定義小數數位的預設數目。CurrencyDecimalDigits, to define the default number of fractional digits.

CurrencyDecimalSeparator 定義小數分隔符號。CurrencyDecimalSeparator, to define the decimal separator symbol.

CurrencyGroupSeparator,定義群組或千位分隔符號。CurrencyGroupSeparator, to define the group or thousands separator.

CurrencyGroupSizes,定義整數群組的大小。CurrencyGroupSizes, to define the sizes of integral groups.

CurrencyNegativePattern,定義負數貨幣值的模式。CurrencyNegativePattern, to define the pattern of negative currency values.

CurrencyPositivePattern,定義正貨幣值的模式。CurrencyPositivePattern, to define the pattern of positive currency values.

CurrencySymbol,用來定義貨幣符號。CurrencySymbol, to define the currency symbol.

NegativeSign 定義負號。NegativeSign, to define the negative sign symbol.
"D" 或 "d" (十進位格式規範)"D" or "d" (decimal format specifier) NegativeSign 定義負號。NegativeSign, to define the negative sign symbol.
"E" 或 "e" (指數或科學格式規範)"E" or "e" (exponential or scientific format specifier) NegativeSign,用來定義尾數和指數中的負號符號。NegativeSign, to define the negative sign symbol in the mantissa and exponent.

NumberDecimalSeparator 定義小數分隔符號。NumberDecimalSeparator, to define the decimal separator symbol.

PositiveSign,用來定義指數中的正號符號。PositiveSign, to define the positive sign symbol in the exponent.
"F" 或 "f" (固定點格式規範)"F" or "f" (fixed-point format specifier) NegativeSign 定義負號。NegativeSign, to define the negative sign symbol.

NumberDecimalDigits,用來定義小數數位的預設數目。NumberDecimalDigits, to define the default number of fractional digits.

NumberDecimalSeparator 定義小數分隔符號。NumberDecimalSeparator, to define the decimal separator symbol.
"G" 或 "g" (一般格式規範)"G" or "g" (general format specifier) NegativeSign 定義負號。NegativeSign, to define the negative sign symbol.

NumberDecimalSeparator 定義小數分隔符號。NumberDecimalSeparator, to define the decimal separator symbol.

PositiveSign,以指數格式定義結果字串的正號符號。PositiveSign, to define the positive sign symbol for result strings in exponential format.
"N" 或 "n" (數位格式規範)"N" or "n" (number format specifier) NegativeSign 定義負號。NegativeSign, to define the negative sign symbol.

NumberDecimalDigits,用來定義小數數位的預設數目。NumberDecimalDigits, to define the default number of fractional digits.

NumberDecimalSeparator 定義小數分隔符號。NumberDecimalSeparator, to define the decimal separator symbol.

NumberGroupSeparator,定義群組分隔符號(千位)符號。NumberGroupSeparator, to define the group separator (thousands) symbol.

NumberGroupSizes,定義群組中的整數位數。NumberGroupSizes, to define the number of integral digits in a group.

NumberNegativePattern,定義負數值的格式。NumberNegativePattern, to define the format of negative values.
"P" 或 "p" (百分比格式規範)"P" or "p" (percent format specifier) NegativeSign 定義負號。NegativeSign, to define the negative sign symbol.

PercentDecimalDigits,用來定義小數數位的預設數目。PercentDecimalDigits, to define the default number of fractional digits.

PercentDecimalSeparator 定義小數分隔符號。PercentDecimalSeparator, to define the decimal separator symbol.

PercentGroupSeparator,用來定義群組分隔符號號。PercentGroupSeparator, to define the group separator symbol.

PercentGroupSizes,定義群組中的整數位數。PercentGroupSizes, to define the number of integral digits in a group.

PercentNegativePattern,定義百分比符號的位置和負數值的負號。PercentNegativePattern, to define the placement of the percent symbol and the negative symbol for negative values.

PercentPositivePattern,定義正數值的百分比符號位置。PercentPositivePattern, to define the placement of the percent symbol for positive values.

PercentSymbol,用來定義百分比符號。PercentSymbol, to define the percent symbol.
"R" 或 "r" (來回格式規範)"R" or "r" (round-trip format specifier) NegativeSign 定義負號。NegativeSign, to define the negative sign symbol.

NumberDecimalSeparator 定義小數分隔符號。NumberDecimalSeparator, to define the decimal separator symbol.

PositiveSign,用來定義指數中的正號符號。PositiveSign, to define the positive sign symbol in an exponent.
"X" 或 "x" (十六進位格式規範)"X" or "x" (hexadecimal format specifier) 無。None.
"."(小數點自訂格式規範)"." (decimal point custom format specifier) NumberDecimalSeparator 定義小數分隔符號。NumberDecimalSeparator, to define the decimal separator symbol.
"," (群組分隔符號自訂格式規範)"," (group separator custom format specifier) NumberGroupSeparator,用來定義群組(千位)分隔符號號。NumberGroupSeparator, to define the group (thousands) separator symbol.
"%" (百分比預留位置自訂格式規範)"%" (percentage placeholder custom format specifier) PercentSymbol,用來定義百分比符號。PercentSymbol, to define the percent symbol.
"‰" (每千個預留位置自訂格式規範)"‰" (per mille placeholder custom format specifier) PerMilleSymbol,用來定義每個千位符號。PerMilleSymbol, to define the per mille symbol.
"E" (指數標記法自訂格式規範)"E" (exponential notation custom format specifier) NegativeSign,用來定義尾數和指數中的負號符號。NegativeSign, to define the negative sign symbol in the mantissa and exponent.

PositiveSign,用來定義指數中的正號符號。PositiveSign, to define the positive sign symbol in the exponent.

請注意, NumberFormatInfo類別NativeDigits包含屬性,可指定特定文化特性所使用的基底10位數。Note that the NumberFormatInfo class includes a NativeDigits property that specifies the base 10 digits used by a specific culture. 不過,屬性不會用於格式化作業;結果字串中只會使用基本拉丁數位0(U + 0030)到9(U + 0039)。However, the property is not used in formatting operations; only the Basic Latin digits 0 (U+0030) through 9 (U+0039) are used in the result string. 此外,對於、 Single NaN Double NaNSymbol PositiveInfinitySymbol NegativeInfinitySymbol和的和值,結果字串只包含由、和屬性所定義的符號。 PositiveInfinity NegativeInfinity各自.In addition, for Single and Double values of NaN, PositiveInfinity, and NegativeInfinity, the result string consists exclusively of the symbols defined by the NaNSymbol, PositiveInfinitySymbol, and NegativeInfinitySymbol properties, respectively.

修改 NumberFormatInfo 屬性Modifying NumberFormatInfo properties

您可以修改NumberFormatInfo物件的屬性,以自訂數值格式化作業所產生的結果字串。You can modify the properties of a NumberFormatInfo object to customize the result string produced in a numeric formatting operation. 若要這樣做:To do this:

  1. 建立您想要修改其格式化慣例NumberFormatInfo之物件的讀取/寫入複本。Create a read/write copy of a NumberFormatInfo object whose formatting conventions you want to modify. 如需詳細資訊,請參閱將NumberFormatInfo 物件具現化一節。For more information, see the Instantiating a NumberFormatInfo object section.

  2. 修改用來產生所需結果字串的屬性或屬性。Modify the property or properties that are used to produce the desired result string. 如需格式化方法如何使用NumberFormatInfo屬性來定義結果字串的詳細資訊,請參閱格式字串和 NumberFormatInfo 屬性一節。For information about how formatting methods use NumberFormatInfo properties to define result strings, see the Format strings and NumberFormatInfo properties section.

  3. 在格式化方法NumberFormatInfo的呼叫中IFormatProvider ,使用自訂物件做為引數。Use the custom NumberFormatInfo object as the IFormatProvider argument in calls to formatting methods.

注意

不需要在每次啟動應用程式時動態修改文化特性的屬性值,您可以使用CultureAndRegionInfoBuilder類別來定義自訂文化特性(具有唯一名稱並補充現有文化特性的文化特性)或取代culture (用來取代特定文化特性的文化特性)。Instead of dynamically modifying a culture's property values each time an application is started, you can use the CultureAndRegionInfoBuilder class to define either a custom culture (a culture that has a unique name and that supplements existing cultures) or a replacement culture (one that is used instead of a specific culture).

下列各節提供一些範例。The following sections provide some examples.

修改貨幣符號和模式Modifying the currency symbol and pattern

下列範例會修改NumberFormatInfo代表 en-us 文化特性之格式化慣例的物件。The following example modifies a NumberFormatInfo object that represents the formatting conventions of the en-US culture. 它會將 ISO-4217 貨幣符號指派給CurrencySymbol屬性,並定義貨幣值的模式,其中包含貨幣符號,後面接著空格和數值。It assigns the ISO-4217 currency symbol to the CurrencySymbol property and defines a pattern for currency values that consists of the currency symbol followed by a space and a numeric value.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      // Retrieve a writable NumberFormatInfo object.
      CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US");
      NumberFormatInfo nfi = enUS.NumberFormat;

      // Use the ISO currency symbol instead of the native currency symbol.
      nfi.CurrencySymbol =  (new RegionInfo(enUS.Name)).ISOCurrencySymbol;
      // Change the positive currency pattern to <code><space><value>.
      nfi.CurrencyPositivePattern = 2;
      // Change the negative currency pattern to <code><space><sign><value>.     
      nfi.CurrencyNegativePattern = 12;
      
      // Produce the result strings by calling ToString.
      Decimal[] values = { 1065.23m, 19.89m, -.03m, -175902.32m };
      foreach (var value in values)
         Console.WriteLine(value.ToString("C", enUS));

      Console.WriteLine();
      
      // Produce the result strings by calling a composite formatting method.
      foreach (var value in values)
         Console.WriteLine(String.Format(enUS, "{0:C}", value));      
   }
}
// The example displays the following output:
//       USD 1,065.23
//       USD 19.89
//       USD -0.03
//       USD -175,902.32
//       
//       USD 1,065.23
//       USD 19.89
//       USD -0.03
//       USD -175,902.32
Imports System.Globalization

Module Example
   Public Sub Main()
      ' Retrieve a writable NumberFormatInfo object.
      Dim enUS As CultureInfo = CultureInfo.CreateSpecificCulture("en-US")
      Dim nfi As NumberFormatInfo = enUS.NumberFormat

      ' Use the ISO currency symbol instead of the native currency symbol.
      nfi.CurrencySymbol =  (New RegionInfo(enUS.Name)).ISOCurrencySymbol
      ' Change the positive currency pattern to <code><space><value>.
      nfi.CurrencyPositivePattern = 2
      ' Change the negative currency pattern to <code><space><sign><value>.     
      nfi.CurrencyNegativePattern = 12
      
      ' Produce the result strings by calling ToString.
      Dim values() As Decimal = { 1065.23d, 19.89d, -.03d, -175902.32d }
      For Each value In values
         Console.WriteLine(value.ToString("C", enUS))
      Next      
      Console.WriteLine()
      
      ' Produce the result strings by calling a composite formatting method.
      For Each value In values
         Console.WriteLine(String.Format(enUS, "{0:C}", value))      
      Next
   End Sub
End Module
' The example displays the following output:
'       USD 1,065.23
'       USD 19.89
'       USD -0.03
'       USD -175,902.32
'       
'       USD 1,065.23
'       USD 19.89
'       USD -0.03
'       USD -175,902.32

格式化國家(地區)識別碼Formatting a national identification number

許多國家(地區)的識別碼只包含數位,因此可以藉由修改NumberFormatInfo物件的屬性,輕鬆地將其格式化。Many national identification numbers consist exclusively of digits and so can easily be formatted by modifying the properties of a NumberFormatInfo object. 例如,美國的社會安全號碼是由9位數排列,如下所示: XXX-XX-XXXXFor example, a social security number in the United States consists of 9 digits arranged as follows: XXX-XX-XXXX. 下列範例假設社會安全號碼會儲存為整數值,並適當地進行格式化。The following example assumes that social security numbers are stored as integer values and formats them appropriately.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      // Instantiate a read-only NumberFormatInfo object.
      CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US");
      NumberFormatInfo nfi = enUS.NumberFormat;

      // Modify the relevant properties.
      nfi.NumberGroupSeparator = "-";
      nfi.NumberGroupSizes = new int[] { 3, 2, 4};
      nfi.NumberDecimalDigits = 0;
      
      int[] ids = { 111223333, 999776666 };
      
      // Produce the result string by calling ToString.
      foreach (var id in ids)
         Console.WriteLine(id.ToString("N", enUS));

      Console.WriteLine();
      
      // Produce the result string using composite formatting.
      foreach (var id in ids)
         Console.WriteLine(String.Format(enUS, "{0:N}", id));
   }
}
// The example displays the following output:
//       1112-23-333
//       9997-76-666
//       
//       1112-23-333
//       9997-76-666
Imports System.Globalization

Module Example
   Public Sub Main()
      ' Instantiate a read-only NumberFormatInfo object.
      Dim enUS As CultureInfo = CultureInfo.CreateSpecificCulture("en-US")
      Dim nfi As NumberFormatInfo = enUS.NumberFormat

      ' Modify the relevant properties.
      nfi.NumberGroupSeparator = "-"
      nfi.NumberGroupSizes = { 3, 2, 4}
      nfi.NumberDecimalDigits = 0
      
      Dim ids() As Integer = { 111223333, 999776666 }
      
      ' Produce the result string by calling ToString.
      For Each id In ids
         Console.WriteLine(id.ToString("N", enUS))
      Next 
      Console.WriteLine()
      
      ' Produce the result string using composite formatting.
      For Each id In ids
         Console.WriteLine(String.Format(enUS, "{0:N}", id))
      Next
   End Sub
End Module
' The example displays the following output:
'       1112-23-333
'       9997-76-666
'       
'       1112-23-333
'       9997-76-666

剖析數值字串Parsing numeric strings

剖析包含將數位的字串表示轉換成數位。Parsing involves converting the string representation of a number to a number. .NET Framework 中的每個數數值型別都包含兩個多ParseTryParse剖析方法:和。Each numeric type in the .NET Framework includes two overloaded parsing methods: Parse and TryParse. Parse方法會將字串轉換成數位,如果轉換失敗,則會擲回例外狀況。The Parse method converts a string to a number and throws an exception if the conversion fails. 方法會將字串轉換成數位,將數位指派outBoolean引數,並傳回值,指出轉換是否成功。 TryParseThe TryParse method converts a string to a number, assigns the number to an out argument, and returns a Boolean value that indicates whether the conversion succeeded.

剖析方法會隱含或明確地使用NumberStyles列舉值,以決定當剖析作業成功時,可以在字串中顯示哪些樣式元素(例如群組分隔符號、十進位分隔符號或貨幣符號)。The parsing methods implicitly or explicitly use a NumberStyles enumeration value to determine what style elements (such as group separators, a decimal separator, or a currency symbol) can be present in a string if the parsing operation is to succeed. 如果方法呼叫中未提供NumberStyles Float AllowThousands值,則預設值為,其中包含和旗標,其指定剖析的字串可以包含群組符號、小數分隔符號、負號、 NumberStyles和空白字元,也可以是以指數標記法表示之數位的字串。If a NumberStyles value is not provided in the method call, the default is a NumberStyles value that includes the Float and AllowThousands flags, which specifies that the parsed string can include group symbols, a decimal separator, a negative sign, and white-space characters, or it can be the string representation of a number in exponential notation.

剖析方法也會隱含或明確地使用NumberFormatInfo物件,以定義可在要剖析的字串中出現的特定符號和模式。The parsing methods also implicitly or explicitly use a NumberFormatInfo object that defines the specific symbols and patterns that can occur in the string to be parsed. 如果未提供NumberFormatInfo 物件,預設值為目前線程NumberFormatInfo文化特性的。If a NumberFormatInfo object is not provided, the default is the NumberFormatInfo for the current thread culture. 如需剖析的詳細資訊,請參閱個別剖析方法,例如Int16.Parse(String)Int32.Parse(String, NumberStyles)Int64.Parse(String, IFormatProvider)Decimal.Parse(String, NumberStyles, IFormatProvider)Double.TryParse(String, Double)BigInteger.TryParse(String, NumberStyles, IFormatProvider, BigInteger)For more information about parsing, see the individual parsing methods, such as Int16.Parse(String), Int32.Parse(String, NumberStyles), Int64.Parse(String, IFormatProvider), Decimal.Parse(String, NumberStyles, IFormatProvider), Double.TryParse(String, Double), and BigInteger.TryParse(String, NumberStyles, IFormatProvider, BigInteger).

下列範例說明剖析字串的區分文化特性本質。The following example illustrates the culture-sensitive nature of parsing strings. 它會使用 en-us、fr-fr 和非變異文化特性的慣例,嘗試剖析包含千位分隔符號的字串。It tries to parse a string that include thousands separators by using the conventions of the en-US, fr-FR, and invariant cultures. 包含逗號做為群組分隔符號的字串,以及小數分隔符號的句號無法以 fr-fr 文化特性進行剖析,而包含空白字元的字串做為群組分隔符號,而逗號做為小數分隔符號,則無法在 en-us 和不變的文化特性中進行剖析。A string that includes the comma as a group separator and the period as a decimal separator fails to parse in the fr-FR culture, and a string with white space as a group separator and a comma as a decimal separator fails to parse in the en-US and invariant cultures.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      String[] values = { "1,034,562.91", "9 532 978,07" };
      String[] cultureNames = { "en-US", "fr-FR", "" };
      
      foreach (var value in values) {
         foreach (var cultureName in cultureNames) {
            CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName);
            String name = culture.Name == "" ? "Invariant" : culture.Name;
            try {
               Decimal amount = Decimal.Parse(value, culture);
               Console.WriteLine("'{0}' --> {1} ({2})", value, amount, name);
            }
            catch (FormatException) {
               Console.WriteLine("'{0}': FormatException ({1})",
                                 value, name);
            }   
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//       '1,034,562.91' --> 1034562.91 (en-US)
//       '1,034,562.91': FormatException (fr-FR)
//       '1,034,562.91' --> 1034562.91 (Invariant)
//       
//       '9 532 978,07': FormatException (en-US)
//       '9 532 978,07' --> 9532978.07 (fr-FR)
//       '9 532 978,07': FormatException (Invariant)
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim values() As String = { "1,034,562.91", "9 532 978,07" }
      Dim cultureNames() As String = { "en-US", "fr-FR", "" }
      
      For Each value In values
         For Each cultureName In cultureNames
            Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture(cultureName)
            Dim name As String = If(culture.Name = "", "Invariant", culture.Name)
            Try
               Dim amount As Decimal = Decimal.Parse(value, culture)
               Console.WriteLine("'{0}' --> {1} ({2})", value, amount, name)
            Catch e As FormatException
               Console.WriteLine("'{0}': FormatException ({1})",
                                 value, name)
            End Try   
         Next
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output:
'       '1,034,562.91' --> 1034562.91 (en-US)
'       '1,034,562.91': FormatException (fr-FR)
'       '1,034,562.91' --> 1034562.91 (Invariant)
'       
'       '9 532 978,07': FormatException (en-US)
'       '9 532 978,07' --> 9532978.07 (fr-FR)
'       '9 532 978,07': FormatException (Invariant)

剖析通常會發生在兩個內容中:Parsing generally occurs in two contexts:

  • 做為將使用者輸入轉換成數值的作業。As an operation that is designed to convert user input into a numeric value.

  • 當做作業,設計用來反復存取數值;也就是將先前序列化為字串的數值還原序列化。As an operation that is designed to round-trip a numeric value; that is, to deserialize a numeric value that was previously serialized as a string.

下列各節會更詳細地討論這兩項作業。The following sections discuss these two operations in greater detail.

剖析使用者字串Parsing user strings

當您剖析使用者輸入的數值字串時,您應該一律具現化NumberFormatInfo反映使用者文化設定的物件。When you are parsing numeric strings input by the user, you should always instantiate a NumberFormatInfo object that reflects the user's cultural settings. 如需如何具現化NumberFormatInfo反映使用者自訂之物件的相關資訊,請參閱NumberFormatInfo 和動態資料一節。For information about how to instantiate a NumberFormatInfo object that reflects user customizations, see the NumberFormatInfo and dynamic data section.

下列範例說明會反映使用者文化設定的剖析作業與不是其中一項的差異。The following example illustrates the difference between a parsing operation that reflects user cultural settings and one that does not. 在此情況下,預設的系統文化特性為 en-us,但使用者已將 "," 定義為十進位符號,而 "." 則做為 [控制台]、[地區和語言] 中的群組分隔符號。In this case, the default system culture is en-US, but the user has defined "," as the decimal symbol and "." as the group separator in Control Panel, Region and Language. 一般來說,這些符號會以預設的 en-us 文化特性反轉。Ordinarily, these symbols are reversed in the default en-US culture. 當使用者輸入反映使用者設定的字串,且該字串由NumberFormatInfo同時反映使用者設定(覆寫)的物件進行剖析時,剖析作業會傳回正確的結果。When the user enters a string that reflects user settings, and the string is parsed by a NumberFormatInfo object that also reflects user settings (overrides), the parsing operation returns a correct result. 不過,當字串由NumberFormatInfo反映標準 en-us 文化特性設定的物件進行剖析時,會造成群組分隔符號的逗號符號錯誤,並傳回不正確的結果。However, when the string is parsed by a NumberFormatInfo object that reflects standard en-US cultural settings, it mistakes the comma symbol for a group separator and returns an incorrect result.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      CultureInfo stdCulture = CultureInfo.GetCultureInfo("en-US");
      CultureInfo custCulture = CultureInfo.CreateSpecificCulture("en-US"); 
            
      String value = "310,16";
      try {
         Console.WriteLine("{0} culture reflects user overrides: {1}", 
                           stdCulture.Name, stdCulture.UseUserOverride);
         Decimal amount = Decimal.Parse(value, stdCulture);
         Console.WriteLine("'{0}' --> {1}", value, amount.ToString(CultureInfo.InvariantCulture));                                                                                        
      }
      catch (FormatException) {
         Console.WriteLine("Unable to parse '{0}'", value);
      }    
      Console.WriteLine();
                                            
      try {
         Console.WriteLine("{0} culture reflects user overrides: {1}", 
                           custCulture.Name, custCulture.UseUserOverride);
         Decimal amount = Decimal.Parse(value, custCulture);
         Console.WriteLine("'{0}' --> {1}", value, amount.ToString(CultureInfo.InvariantCulture));                                                                                        
      }
      catch (FormatException) {
         Console.WriteLine("Unable to parse '{0}'", value);
      }   
   }
}
// The example displays the following output:
//       en-US culture reflects user overrides: False
//       '310,16' --> 31016
//       
//       en-US culture reflects user overrides: True
//       '310,16' --> 310.16
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim stdCulture As CultureInfo = CultureInfo.GetCultureInfo("en-US")
      Dim custCulture As CultureInfo = CultureInfo.CreateSpecificCulture("en-US") 
            
      Dim value As String = "310,16"
      Try
         Console.WriteLine("{0} culture reflects user overrides: {1}", 
                           stdCulture.Name, stdCulture.UseUserOverride)
         Dim amount As Decimal = Decimal.Parse(value, stdCulture)
         Console.WriteLine("'{0}' --> {1}", value, amount.ToString(CultureInfo.InvariantCulture))                                                                                        
      Catch e As FormatException
         Console.WriteLine("Unable to parse '{0}'", value)
      End Try   
      Console.WriteLine()
                                            
      Try
         Console.WriteLine("{0} culture reflects user overrides: {1}", 
                           custCulture.Name, custCulture.UseUserOverride)
         Dim amount As Decimal = Decimal.Parse(value, custCulture)
         Console.WriteLine("'{0}' --> {1}", value, amount.ToString(CultureInfo.InvariantCulture))                                                                                        
      Catch e As FormatException
         Console.WriteLine("Unable to parse '{0}'", value)
      End Try   
   End Sub
End Module
' The example displays the following output:
'       en-US culture reflects user overrides: False
'       '310,16' --> 31016
'       
'       en-US culture reflects user overrides: True
'       '310,16' --> 310.16

序列化和還原序列化數值資料Serializing and deserializing numeric data

當數值資料以字串格式序列化,並在稍後進行還原序列化和剖析時,應該使用不因文化特性而異的慣例來產生和剖析字串。When numeric data is serialized in string format and later deserialized and parsed, the strings should be generated and parsed by using the conventions of the invariant culture. 格式設定和剖析作業絕對不應反映特定文化特性的慣例。The formatting and parsing operations should never reflect the conventions of a specific culture. 如果使用文化特性專屬的設定,資料的可攜性會受到嚴格的限制;只有在其文化特性設定與序列化所在的執行緒相同的執行緒上,才能成功還原序列化。If culture-specific settings are used, the portability of the data is strictly limited; it can be successfully deserialized only on a thread whose culture-specific settings are identical to those of the thread on which it was serialized. 在某些情況下,這表示資料甚至無法在其序列化所在的同一個系統上成功還原序列化。In some cases, this means that the data cannot even be successfully deserialized on the same system on which it was serialized.

下列範例說明違反此原則時可能發生的狀況。The following example illustrates what can happen when this principle is violated. 當目前的執行緒使用 en-us 文化特性的特定文化特性設定時,陣列中的浮點值會轉換成字串。Floating-point values in an array are converted to strings when the current thread uses the culture-specific settings of the en-US culture. 然後,資料會由使用半 GB 文化特性之文化特性設定的執行緒進行剖析。The data is then parsed by a thread that uses the culture-specific settings of the en-GB culture. 在此情況下,雖然每個剖析作業都會成功,但資料不會成功地往返,而且會發生資料損毀。In this case, although each parsing operation succeeds, the data does not round-trip successfully and data corruption occurs. 在其他情況下,剖析作業可能會失敗, FormatException而且可能會擲回例外狀況。In other cases, a parsing operation could fail and a FormatException exception could be thrown.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;

public class Example
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
      PersistData();
      
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
      RestoreData();
   }

   private static void PersistData()
   {
      // Define an array of floating-point values.
      Double[] values = { 160325.972, 8631.16, 1.304e5, 98017554.385, 
                          8.5938287084321676e94 };
      Console.WriteLine("Original values: ");
      foreach (var value in values) 
         Console.WriteLine(value.ToString("R", CultureInfo.InvariantCulture));
         
      // Serialize an array of doubles to a file 
      StreamWriter sw = new StreamWriter(@".\NumericData.bin");
      for (int ctr = 0; ctr < values.Length; ctr++) {
         sw.Write(values[ctr].ToString("R"));
         if (ctr < values.Length - 1) sw.Write("|");
      }
      sw.Close();
      Console.WriteLine();
   }
   
   private static void RestoreData()
   {   
      // Deserialize the data
      StreamReader sr = new StreamReader(@".\NumericData.bin");
      String data = sr.ReadToEnd();
      sr.Close();
      
      String[] stringValues = data.Split('|');
      List<Double> newValueList = new List<Double>();
      
      foreach (var stringValue in stringValues) {
         try {
            newValueList.Add(Double.Parse(stringValue));
         }
         catch (FormatException) {
            newValueList.Add(Double.NaN);
         }   
      }                                   

      Console.WriteLine("Restored values:");
      foreach (var newValue in newValueList) 
         Console.WriteLine(newValue.ToString("R", NumberFormatInfo.InvariantInfo));
   }
}
// The example displays the following output:
//       Original values:
//       160325.972
//       8631.16
//       130400
//       98017554.385
//       8.5938287084321671E+94
//       
//       Restored values:
//       160325972
//       863116
//       130400
//       98017554385
//       8.5938287084321666E+110
Imports System.Collections.Generic
Imports System.Globalization
Imports System.IO
Imports System.Threading

Module Example
   Public Sub Main()
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
      PersistData()
      
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")
      RestoreData()
   End Sub
   
   Private Sub PersistData()
      ' Define an array of floating-point values.
      Dim values() As Double = { 160325.972, 8631.16, 1.304e5, 98017554.385, 
                                 8.5938287084321676e94 }
      Console.WriteLine("Original values: ")
      For Each value In values
         Console.WriteLine(value.ToString("R", CultureInfo.InvariantCulture))
      Next
         
      ' Serialize an array of doubles to a file 
      Dim sw As New StreamWriter(".\NumericData.bin")
      For ctr As Integer = 0 To values.Length - 1
         sw.Write(values(ctr).ToString("R"))
         If ctr < values.Length - 1 Then sw.Write("|")
      Next
      sw.Close()
      Console.WriteLine()
   End Sub
   
   Private Sub RestoreData()   
      ' Deserialize the data
      Dim sr AS New StreamReader(".\NumericData.bin")
      Dim data As String = sr.ReadToEnd()
      sr.Close()
      
      Dim stringValues() As String = data.Split("|"c)
      Dim newValueList As New List(Of Double)
      
      For Each stringValue In stringValues
         Try
            newValueList.Add(Double.Parse(stringValue))
         Catch e As FormatException
            newValueList.Add(Double.NaN)
         End Try   
      Next                                   

      Console.WriteLine("Restored values:")
      For Each newValue In newValueList
         Console.WriteLine(newValue.ToString("R", NumberFormatInfo.InvariantInfo))
      Next
   End Sub
End Module
' The example displays the following output:
'       Original values:
'       160325.972
'       8631.16
'       130400
'       98017554.385
'       8.5938287084321671E+94
'       
'       Restored values:
'       160325972
'       863116
'       130400
'       98017554385
'       8.5938287084321666E+110

建構函式

NumberFormatInfo()

初始化與文化特性無關 (不因文化特性而異) 之 NumberFormatInfo 類別的可寫入新執行個體。Initializes a new writable instance of the NumberFormatInfo class that is culture-independent (invariant).

屬性

CurrencyDecimalDigits

取得或設定要在貨幣值中使用的小數位數。Gets or sets the number of decimal places to use in currency values.

CurrencyDecimalSeparator

取得或設定要做為貨幣值中小數分隔符號的字串。Gets or sets the string to use as the decimal separator in currency values.

CurrencyGroupSeparator

取得或設定分隔貨幣值中小數點左邊數字群組的字串。Gets or sets the string that separates groups of digits to the left of the decimal in currency values.

CurrencyGroupSizes

取得或設定貨幣值內小數點左邊數字的各個群組中的位數。Gets or sets the number of digits in each group to the left of the decimal in currency values.

CurrencyNegativePattern

取得或設定負數貨幣值的格式模式。Gets or sets the format pattern for negative currency values.

CurrencyPositivePattern

取得或設定正數貨幣值的格式模式。Gets or sets the format pattern for positive currency values.

CurrencySymbol

取得或設定要做為貨幣符號的字串。Gets or sets the string to use as the currency symbol.

CurrentInfo

取得根據目前文化特性格式化值的唯讀 NumberFormatInfoGets a read-only NumberFormatInfo that formats values based on the current culture.

DigitSubstitution

取得或設定數值,指定圖形使用者介面顯示數字圖案的方式。Gets or sets a value that specifies how the graphical user interface displays the shape of a digit.

InvariantInfo

取得與文化特性無關 (非變異) 的唯讀 NumberFormatInfo 物件。Gets a read-only NumberFormatInfo object that is culture-independent (invariant).

IsReadOnly

取得值,表示這個 NumberFormatInfo 物件是否為唯讀。Gets a value that indicates whether this NumberFormatInfo object is read-only.

NaNSymbol

取得或設定代表 IEEE NaN (Not a Number) 值的字串。Gets or sets the string that represents the IEEE NaN (not a number) value.

NativeDigits

取得或設定字串陣列,其中包含對等於西方數字 0 到 9 之當地慣用的數字。Gets or sets a string array of native digits equivalent to the Western digits 0 through 9.

NegativeInfinitySymbol

取得或設定代表負無限大的字串。Gets or sets the string that represents negative infinity.

NegativeSign

取得或設定代表相關數字為負數的字串。Gets or sets the string that denotes that the associated number is negative.

NumberDecimalDigits

取得或設定要在數值中使用的小數位數。Gets or sets the number of decimal places to use in numeric values.

NumberDecimalSeparator

取得或設定要做為數值中小數分隔符號的字串。Gets or sets the string to use as the decimal separator in numeric values.

NumberGroupSeparator

取得或設定分隔數值中小數點左邊數字群組的字串。Gets or sets the string that separates groups of digits to the left of the decimal in numeric values.

NumberGroupSizes

取得或設定數值內小數點左邊數字的各個群組中的位數。Gets or sets the number of digits in each group to the left of the decimal in numeric values.

NumberNegativePattern

取得或設定負數值的格式模式。Gets or sets the format pattern for negative numeric values.

PercentDecimalDigits

取得或設定要在百分比值中使用的小數位數。Gets or sets the number of decimal places to use in percent values.

PercentDecimalSeparator

取得或設定要做為百分比值中小數分隔符號使用的字串。Gets or sets the string to use as the decimal separator in percent values.

PercentGroupSeparator

取得或設定百分比值中分隔小數點左邊數字群組的字串。Gets or sets the string that separates groups of digits to the left of the decimal in percent values.

PercentGroupSizes

取得或設定百分比值內小數點左邊數字的各個群組中的位數。Gets or sets the number of digits in each group to the left of the decimal in percent values.

PercentNegativePattern

取得或設定負數百分比值的格式模式。Gets or sets the format pattern for negative percent values.

PercentPositivePattern

取得或設定正數百分比值的格式模式。Gets or sets the format pattern for positive percent values.

PercentSymbol

取得或設定要當做百分比符號的字串。Gets or sets the string to use as the percent symbol.

PerMilleSymbol

取得或設定要當做千分之一符號的字串。Gets or sets the string to use as the per mille symbol.

PositiveInfinitySymbol

取得或設定代表正無限大的字串。Gets or sets the string that represents positive infinity.

PositiveSign

取得或設定用來表示相關數字為正數的字串。Gets or sets the string that denotes that the associated number is positive.

方法

Clone()

建立 NumberFormatInfo 物件的淺層複本 (Shallow Copy)。Creates a shallow copy of the NumberFormatInfo object.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetFormat(Type)

取得指定類型的物件,以提供數字格式化服務。Gets an object of the specified type that provides a number formatting service.

GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetInstance(IFormatProvider)

取得與指定的 NumberFormatInfo 相關聯的 IFormatProviderGets the NumberFormatInfo associated with the specified IFormatProvider.

GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
ReadOnly(NumberFormatInfo)

傳回唯讀的 NumberFormatInfo 包裝函式。Returns a read-only NumberFormatInfo wrapper.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

適用於

另請參閱