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 USD,而不是默认值 $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. 下面的示例为当前区域性为英语(美国)并且其货币符号已从默认值更改为 USD 的系统提供了一个图例。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: $

CultureInfo.DateTimeFormat CultureInfo.TextInfo CultureInfo.NumberFormat如果将true属性设置为,则还会从用户设置中检索属性、和。 CultureInfo.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属性列出的日历之一),则方法的结果和属性的值将为尚未.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. 一个NumberFormatInfo对象,该对象表示固定区域性的格式设置约定,可用于在这些操作中,结果字符串不应因区域性而异。A 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 CA 则是表示加拿大所说英语的特定区域性。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对象NumberFormatInfo ,该对象反映属于非特定区域性的特定区域性的格式设置约定,而不是使用泛型值填充对象。Rather 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类提供的数值的区域性特定数据是动态的,就像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 更新包括对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 NoNo
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

NumberFormatInfo对象在所有数字格式设置操作中隐式或显式使用。A NumberFormatInfo object is used implicitly or explicitly in all numeric formatting operations. 其中包括对以下方法的调用:These include calls to the following methods:

所有数字格式设置操作都利用了IFormatProvider实现。All 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[])格式设置信息,而ICustomFormatter方法请求NumberFormatInfoDateTimeFormatInfo对象以及部署.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) en-us 区域性的格式Decimal设置约定,调用方法将值转换为多种不同的字符串表示形式。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()方法时, Decimal将使用常规("G")格式说明符和当前区域性(在此示例中为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 Double NaN PositiveInfinitySymbol NaNSymbol和的值,结果字符串只包含由NegativeInfinitySymbol 、和属性定义的符号。 NegativeInfinity PositiveInfinity分别.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属性来定义结果字符串的信息,请参阅Format string and NumberFormatInfo properties部分。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类来定义自定义区域性(具有唯一名称并补充现有区域性的区域性)或替换,而不是在每次启动应用程序时都动态修改区域性的属性值。区域性(使用而不是特定区域性)。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 中的每个数值类型包括两个重载分析Parse方法TryParse:和。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. 方法将字符串转换为数字,将该数字赋out给参数,并返回一个Boolean指示转换是否成功的值。 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) Int64.Parse(String, IFormatProvider)Double.TryParse(String, Double) Int32.Parse(String, NumberStyles) Decimal.Parse(String, NumberStyles, IFormatProvider)、、、和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 and dynamic data部分。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. 然后,使用 en-us 区域性的区域性特定设置的线程对数据进行分析。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(非数字)值的字符串。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 对象的浅表副本。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 的浅表副本。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)

适用于

另请参阅