NumberFormatInfo 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
提供文化特性特定的格式和剖析數值資訊。
public ref class NumberFormatInfo sealed : IFormatProvider
public ref class NumberFormatInfo sealed : ICloneable, IFormatProvider
public sealed class NumberFormatInfo : IFormatProvider
public sealed class NumberFormatInfo : ICloneable, IFormatProvider
[System.Serializable]
public sealed class NumberFormatInfo : ICloneable, IFormatProvider
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class NumberFormatInfo : ICloneable, IFormatProvider
type NumberFormatInfo = class
interface IFormatProvider
type NumberFormatInfo = class
interface ICloneable
interface IFormatProvider
[<System.Serializable>]
type NumberFormatInfo = class
interface ICloneable
interface IFormatProvider
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type NumberFormatInfo = class
interface ICloneable
interface IFormatProvider
Public NotInheritable Class NumberFormatInfo
Implements IFormatProvider
Public NotInheritable Class NumberFormatInfo
Implements ICloneable, IFormatProvider
- 繼承
-
NumberFormatInfo
- 屬性
- 實作
範例
下列範例示範如何取得 NumberFormatInfo 對應物件的物件 CultureInfo ,並使用抓取的物件來查詢特定文化特性的數位格式資訊。
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類別包含當您格式化和剖析數值時,所使用的特定文化特性資訊。 此資訊包括貨幣符號、十進位符號、群組分隔符號符號,以及正負號和正負號的符號。
具現化 >numberformatinfo 物件
您可以具現化 NumberFormatInfo 物件,該物件表示目前文化特性的格式化慣例、不因文化特性而異、特定文化特性或中立文化特性。
為目前的文化特性具現化 >numberformatinfo 物件
您可以 NumberFormatInfo 使用下列任何一種方式,為目前的文化特性具現化物件。 在每個案例中,傳回的 NumberFormatInfo 物件都是唯讀的。
從屬性中取出 CultureInfo 代表目前文化特性的物件 CultureInfo.CurrentCulture ,並 CultureInfo 從其屬性抓取物件 CultureInfo.NumberFormat 。
藉由 NumberFormatInfo
static
Shared
在 Visual Basic) 屬性中取出 (所傳回的物件 CurrentInfo 。藉由以 GetInstance 代表目前文化特性的物件來呼叫方法 CultureInfo 。
下列範例會使用這三種方法來建立 NumberFormatInfo 物件,這些物件代表目前文化特性的格式化慣例。 它也會抓取 IsReadOnly 屬性值,以說明每個物件都是唯讀的。
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 物件,以代表目前文化特性的慣例:
藉由使用 NumberFormatInfo 上述程式碼範例中所示的任何方式來抓取物件,並在 Clone 傳回的物件上呼叫方法 NumberFormatInfo 。 這會建立原始物件的複本 NumberFormatInfo ,但它的 IsReadOnly 屬性是
false
。藉由呼叫 CultureInfo.CreateSpecificCulture 方法來建立 CultureInfo 代表目前文化特性的物件,然後使用其 CultureInfo.NumberFormat 屬性來取得 NumberFormatInfo 物件。
下列範例將說明這兩種具現化 NumberFormatInfo 物件的方法,並顯示其屬性的值, IsReadOnly 以說明物件不是唯讀的。
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 透過主控台中的 [區域] 和 [語言] 專案,覆寫一些用於數值格式和剖析作業的屬性值。 例如,如果使用者的文化特性是英文 (美國) 可能會選擇將貨幣值顯示為1.1 美元,而不是預設值 $1.1。 NumberFormatInfo以先前討論的方式抓取的物件會反映這些使用者覆寫。 如果不想要,您可以建立不 NumberFormatInfo 反映使用者覆寫的物件 (而且也可以讀取/寫入,而不是唯讀) ,方法是呼叫函式 CultureInfo.CultureInfo(String, Boolean) 並 false
為引數提供的值 useUserOverride
。 下列範例會針對目前的文化特性是英文 (美國) ,而且其貨幣符號已從預設值 $ 變更為美元的系統提供圖例。
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.UseUserOverride 屬性設定為 true
,則 CultureInfo.DateTimeFormat CultureInfo.NumberFormat CultureInfo.TextInfo 也會從使用者設定中取出屬性、和。 如果使用者設定與物件相關聯的文化特性不相容 CultureInfo (例如,如果選取的行事曆不是屬性) 所列的其中一個行事曆 OptionalCalendars ,則方法的結果和屬性的值都是未定義的。
為非變異文化特性具現化 >numberformatinfo 物件
不因文化特性而異,表示文化特性不區分文化特性。 它是以英文語言為基礎,而不是任何特定英文的國家/地區。 雖然特定文化特性的資料可以是動態的,而且可以變更以反映新的文化特性或使用者喜好設定,但不因文化特性而異的資料並不會變更。 NumberFormatInfo物件,表示不因文化特性而異的格式設定慣例可用於格式化作業,這些作業的結果字串應該不會因文化特性而異。
您可以利用下列方式,具現化表示非變異 NumberFormatInfo 文化特性之格式慣例的物件:
藉由取出屬性的值 InvariantInfo 。 傳回的 NumberFormatInfo 物件是唯讀的。
CultureInfo.NumberFormat從屬性傳回的物件中,抓取屬性的值 CultureInfo CultureInfo.InvariantCulture 。 傳回的 NumberFormatInfo 物件是唯讀的。
藉由呼叫無參數類別的函式 NumberFormatInfo 。 傳回的 NumberFormatInfo 物件是讀取/寫入。
下列範例會使用每個方法來具現化代表不因文化特性而異的 NumberFormatInfo 物件。 接著,它會指出物件是否為唯讀。
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 物件
特定文化特性代表在特定國家/地區中說出的語言。 例如,en-us 是特定的文化特性,代表在美國說出的英文語言,而 en-us 則是特定的文化特性,代表加拿大所說的英文語言。 您可以利用下列方式具現化 NumberFormatInfo 表示特定文化特性之格式慣例的物件:
藉由呼叫 CultureInfo.GetCultureInfo(String) 方法,並抓取傳回 CultureInfo 物件之屬性的值 NumberFormat 。 傳回的 NumberFormatInfo 物件是唯讀的。
傳遞 CultureInfo 物件,代表您要取得其物件的文化特性(culture) NumberFormatInfo 至靜態 GetInstance 方法。 傳回的 NumberFormatInfo 物件是讀取/寫入。
藉由呼叫 CultureInfo.CreateSpecificCulture 方法,並抓取傳回 CultureInfo 物件之屬性的值 NumberFormat 。 傳回的 NumberFormatInfo 物件是讀取/寫入。
藉由呼叫其中一個類別的函式 CultureInfo.CultureInfo ,並取出傳回物件之屬性的值 CultureInfo NumberFormat 。 傳回的 NumberFormatInfo 物件是讀取/寫入。
下列範例會使用這四種方式來建立 NumberFormatInfo 物件,以反映印尼 (印尼) 文化特性的格式化慣例。 它也會指出每個物件是否為唯讀。
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 物件
中立文化特性代表與國家/地區無關的文化特性或語言。 它通常是一或多個特定文化特性的父系。 例如,fr 是法文語言的中性文化特性,以及 fr-fr 文化特性的父系。 您可以建立一個 NumberFormatInfo 物件來表示中性文化特性的格式化慣例,其方式與建立 NumberFormatInfo 代表特定文化特性之格式慣例的物件相同。
注意
在 .NET Framework 3.5 及更早版本中,嘗試取出 NumberFormatInfo 反映中性文化特性之格式慣例的物件會擲回 NotSupportedException 例外狀況。
不過,因為它與特定的國家/地區無關,所以中立文化缺乏特定文化特性的格式資訊。 NumberFormatInfo.NET Framework NumberFormatInfo 會傳回物件,以反映屬於中性文化特性之子系的特定文化特性的格式慣例,而不是使用泛型值來擴展物件。 例如,中立文化特性的 NumberFormatInfo 物件會反映 en-us 文化特性的格式化慣例,而 fr 文化特性的物件會 NumberFormatInfo 反映 fr-fr 文化特性的格式化慣例。
您可以使用類似下列的程式碼來判斷每個中性文化特性所代表的特定文化特性格式慣例。
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 是動態的,就像類別所提供的文化特性資料一樣 CultureInfo 。 對於 NumberFormatInfo 與特定物件相關聯的物件,您不應該對其值的穩定性做出任何假設 CultureInfo 。 只有不因文化特性而異的資料與其相關聯的 NumberFormatInfo 物件是穩定的。 其他資料可能會在應用程式會話之間變更,甚至在單一會話中變更,原因如下:
系統更新。 文化特性喜好設定,例如貨幣符號或貨幣格式會隨著時間而變更。 發生這種情況時,Windows Update 包含 NumberFormatInfo 特定文化特性的屬性值變更。
取代文化特性。 CultureAndRegionInfoBuilder類別可以用來取代現有文化特性的資料。
對屬性值進行級聯的變更。 許多與文化特性相關的屬性可能會在執行時間變更,因而導致 NumberFormatInfo 資料變更。 例如,您可以透過程式設計方式或透過使用者動作來變更目前的文化特性。 發生這種情況時, NumberFormatInfo 屬性傳回的物件會 CurrentInfo 變更為與目前文化特性相關聯的物件。
使用者喜好設定。 您應用程式的使用者可能會透過主控台中的 [區域] 和 [語言] 選項,覆寫與目前系統文化特性相關聯的一些值。 例如,使用者可能會選擇不同的貨幣符號或不同的十進位分隔符號符號。 如果 CultureInfo.UseUserOverride 屬性設定為
true
(預設值) , NumberFormatInfo 也會從使用者設定中抓取物件的屬性。
從 .NET Framework 2.0 開始, NumberFormatInfo 會在建立物件時,初始化物件的所有使用者可覆寫屬性。 仍有可能發生不一致的情況,因為物件建立或使用者覆寫程式都不是不可部分完成的,而且相關的值在物件建立期間可能會變更。 不過,這些不一致應該非常罕見。
您可以控制使用者覆寫是否反映在 NumberFormatInfo 代表與目前文化特性相同文化特性的物件中。 下表列出可抓取物件的方式 NumberFormatInfo ,並指出產生的物件是否會反映使用者覆寫。
CultureInfo 和 >numberformatinfo 物件的來源 | 反映使用者覆寫 |
---|---|
CultureInfo.CurrentCulture.NumberFormat 屬性 |
是 |
NumberFormatInfo.CurrentInfo 屬性 | 是 |
CultureInfo.CreateSpecificCulture 方法 | 是 |
CultureInfo.GetCultureInfo 方法 | 否 |
CultureInfo(String) 建構函式 | 是 |
CultureInfo.CultureInfo(String, Boolean) 建構函式 | 相依于參數的值 useUserOverride |
除非有一個令人信服的理由,否則當您 NumberFormatInfo 在用戶端應用程式中使用物件來格式化和剖析使用者輸入或顯示數值資料時,您應該遵守使用者覆寫。 針對伺服器應用程式或無人看管的應用程式,您不應該考慮使用者覆寫。 但是,如果您以 NumberFormatInfo 明確或隱含的方式使用物件以字串形式保存數值資料,您應該使用反映不因文化特性而異之 NumberFormatInfo 格式慣例的物件,或者指定您使用的自訂數值格式字串,而不論文化特性為何。
IFormatProvider、>numberformatinfo 和數值格式化
NumberFormatInfo在所有數值格式化作業中,隱含或明確使用物件。 這些包括呼叫下列方法:
所有數值格式化方法,例如 Int32.ToString 、 Double.ToString 和 Convert.ToString(Int32) 。
主要的複合格式方法: String.Format 。
其他複合格式化方法,例如 Console.WriteLine(String, Object[]) 和 StringBuilder.AppendFormat(String, Object[]) 。
所有數值格式化作業都會使用實值 IFormatProvider 。 IFormatProvider介面包含單一方法 GetFormat(Type) 。 這是一種回呼方法,它會傳遞 Type 代表提供格式資訊所需之類型的物件。 方法負責傳回該類型的實例 null
,如果無法提供類型的實例,則為。 .NET Framework 提供兩種 IFormatProvider 格式化數位的設定:
CultureInfo類別,表示特定文化特性 (或特定國家/地區) 中的特定語言。 在數值格式化作業中,方法會傳回與其 CultureInfo.GetFormat NumberFormatInfo 屬性相關聯的物件 CultureInfo.NumberFormat 。
NumberFormatInfo類別,提供與其相關聯文化特性之格式設定慣例的相關資訊。 方法會傳回 NumberFormatInfo.GetFormat 本身的實例。
如果 IFormatProvider 未明確提供實作為格式化方法的執行,則 CultureInfo CultureInfo.CurrentCulture 會使用代表目前文化特性的屬性所傳回的物件。
下列範例說明如何藉 IFormatProvider NumberFormatInfo 由定義自訂的執行,來說明在格式化作業中,介面和類別之間的關聯性 IFormatProvider 。 其 GetFormat 方法會顯示格式化作業所要求之物件的類型名稱。 如果介面正在要求 NumberFormatInfo 物件,這個方法會提供 NumberFormatInfo 目前文化特性的物件。 如範例的輸出所示,方法會 Decimal.ToString(IFormatProvider) 要求 NumberFormatInfo 物件來提供格式設定資訊,而方法會 String.Format(IFormatProvider, String, Object[]) 要求 NumberFormatInfo 和物件,以及 DateTimeFormatInfo ICustomFormatter 執行。
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
如果 IFormatProvider 未在數值格式化方法呼叫中明確提供實值,方法會呼叫 CultureInfo.CurrentCulture.GetFormat
方法,此方法會傳回 NumberFormatInfo 對應至目前文化特性的物件。
格式字串和 >numberformatinfo 屬性
每個格式化作業都會使用標準或自訂數值格式字串,從數位產生結果字串。 在某些情況下,使用格式字串來產生結果字串是明確的,如下列範例所示。 這段程式碼會呼叫 Decimal.ToString(IFormatProvider) 方法, Decimal 使用 en-us 文化特性的格式化慣例,將值轉換成一些不同的字串表示。
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
在其他情況下,格式字串的使用是隱含的。 例如,在下列方法呼叫預設或無參數 Decimal.ToString() 方法 Decimal 時,會使用一般 ( "G" ) 格式規範和目前文化特性(在此案例中為 en-us 文化特性)的慣例來格式化實例的值。
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 屬性來判斷結果字串中所使用的模式或符號。 同樣地,每個自訂數值格式規範("0" 和 "#" 除外)會在結果字串中插入由屬性定義的符號 NumberFormatInfo 。 下表列出標準和自訂數值格式規範,以及其相關聯的 NumberFormatInfo 屬性。 若要變更特定文化特性之結果字串的外觀,請參閱 修改 >numberformatinfo 屬性 一節。 如需有關使用這些格式規範的詳細資訊,請參閱 標準數值格式字串 和 自訂數值格式字串。
格式規範 | 相關聯的屬性 |
---|---|
"C" 或 "c" (貨幣格式規範) | CurrencyDecimalDigits,用來定義小數位數的預設數目。 CurrencyDecimalSeparator 定義小數分隔符號。 CurrencyGroupSeparator,用來定義群組或千位分隔符號。 CurrencyGroupSizes,定義整數群組的大小。 CurrencyNegativePattern,用來定義負貨幣值的模式。 CurrencyPositivePattern,定義正貨幣值的模式。 CurrencySymbol,用來定義貨幣符號。 NegativeSign 定義負號。 |
"D" 或 "d" (十進位格式規範) | NegativeSign 定義負號。 |
"E" 或 "e" (指數或科學格式規範) | NegativeSign,用來定義尾數和指數中的負號符號。 NumberDecimalSeparator 定義小數分隔符號。 PositiveSign,用來定義指數中的正負號符號。 |
"F" 或 "f" (固定點格式規範) | NegativeSign 定義負號。 NumberDecimalDigits,用來定義小數位數的預設數目。 NumberDecimalSeparator 定義小數分隔符號。 |
"G" 或 "g" (一般格式規範) | NegativeSign 定義負號。 NumberDecimalSeparator 定義小數分隔符號。 PositiveSign,用來定義指數格式之結果字串的正負號符號。 |
"N" 或 "n" (數位格式規範) | NegativeSign 定義負號。 NumberDecimalDigits,用來定義小數位數的預設數目。 NumberDecimalSeparator 定義小數分隔符號。 NumberGroupSeparator,用來定義群組分隔符號 (千) 符號。 NumberGroupSizes,用來定義群組中的整數數位。 NumberNegativePattern,用來定義負數值的格式。 |
"P" 或 "p" (百分比格式規範) | NegativeSign 定義負號。 PercentDecimalDigits,用來定義小數位數的預設數目。 PercentDecimalSeparator 定義小數分隔符號。 PercentGroupSeparator,用來定義群組分隔符號號。 PercentGroupSizes,用來定義群組中的整數數位。 PercentNegativePattern,用來定義百分比符號的位置,以及負數值的負號。 PercentPositivePattern,定義正值的百分比符號位置。 PercentSymbol,用來定義百分比符號。 |
"R" 或 "r" (來回行程格式規範) | NegativeSign 定義負號。 NumberDecimalSeparator 定義小數分隔符號。 PositiveSign,用來定義指數中的正負號符號。 |
"X" 或 "x" (十六進位格式規範) | 無。 |
"." (小數點自訂格式規範) | NumberDecimalSeparator 定義小數分隔符號。 |
"," (群組分隔符號自訂格式規範) | NumberGroupSeparator,用來定義群組 (千) 分隔符號號。 |
"%" (百分比預留位置自訂格式規範) | PercentSymbol,用來定義百分比符號。 |
"‰" (每千位預留位置自訂格式規範) | PerMilleSymbol,用來定義每千千的符號。 |
"E" (指數標記法自訂格式規範) | NegativeSign,用來定義尾數和指數中的負號符號。 PositiveSign,用來定義指數中的正負號符號。 |
請注意, NumberFormatInfo 類別包含 NativeDigits 屬性,可指定特定文化特性所使用的基底10位數。 但是,不會在格式化作業中使用屬性;結果字串中只會使用基本拉丁數位 0 (U + 0030) 到 9 (U + 0039) 。 此外,和、和的 Single Double 值 NaN
, PositiveInfinity
NegativeInfinity
結果字串會 NaNSymbol 分別由、和屬性所定義的符號所組成 PositiveInfinitySymbol NegativeInfinitySymbol 。
修改 >numberformatinfo 屬性
您可以修改物件的屬性 NumberFormatInfo ,以自訂數值格式化作業所產生的結果字串。 若要這樣做:
建立 NumberFormatInfo 您想要修改其格式化慣例之物件的讀取/寫入複本。 如需詳細資訊,請參閱具現 化 >numberformatinfo 物件 一節。
修改用來產生所需結果字串的屬性或屬性。 如需格式化方法如何使用 NumberFormatInfo 屬性定義結果字串的詳細資訊,請參閱 Format 字串和 >numberformatinfo 屬性 一節。
使用自訂 NumberFormatInfo 物件做為 IFormatProvider 呼叫格式化方法時的引數。
注意
您可以使用 CultureAndRegionInfoBuilder 類別來定義自訂文化特性, (具有唯一名稱的文化特性,並將現有的文化特性補充) 或取代文化特性 (使用的文化特性,而不是特定文化特性) 的文化特性,而不是在每次啟動應用程式時動態修改文化特性的屬性值。
下列各節提供一些範例。
修改貨幣符號和模式
下列範例 NumberFormatInfo 會修改表示 en-us 文化特性之格式慣例的物件。 它會將 ISO-4217 貨幣符號指派給 CurrencySymbol 屬性,並定義貨幣值的模式,其中包含貨幣符號,後面接著一個空格和一個數位值。
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
格式化國家識別碼
許多國家/地區識別碼都只包含數位,因此可以藉由修改物件的屬性來輕鬆格式化 NumberFormatInfo 。 例如,美國的社會安全號碼包含9個數字,相片順序如下: XXX-XX-XXXX
。 下列範例假設社會安全號碼會儲存為整數值,並適當地進行格式化。
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
剖析數值字串
剖析作業牽涉到將數位的字串表示轉換成數位。 .NET Framework 中的每個數數值型別包含兩個多載剖析方法: Parse
和 TryParse
。 Parse
方法會將字串轉換成數位,如果轉換失敗,則會擲回例外狀況。 TryParse
方法會將字串轉換成數位、將數位指派給 out
引數,並傳回 Boolean 指出轉換是否成功的值。
剖析方法會隱含或明確地使用 NumberStyles 列舉值來判斷 (的樣式元素,例如群組分隔符號、小數分隔符號或貨幣符號) 可在剖析作業成功時出現在字串中。 如果 NumberStyles 方法呼叫中未提供值,預設值就是 NumberStyles 包含和旗標的值,此值會 Float 指定剖析 AllowThousands 的字串可以包含群組符號、十進位分隔符號、負號和空白字元,或者可以是以指數標記法表示之數位的字串表示。
剖析方法也會隱含或明確地使用 NumberFormatInfo 物件,該物件定義可在要剖析的字串中出現的特定符號和模式。 如果 NumberFormatInfo 未提供物件,預設值為 NumberFormatInfo 目前文化特性的。 如需剖析的詳細資訊,請參閱個別的剖析方法,例如、、、 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) 。
下列範例說明剖析字串的區分文化特性本質。 它會嘗試使用 en-us、fr-fr 和非變異文化特性的慣例來剖析包含千位分隔符號的字串。 包含逗點做為群組分隔符號的字串,以及做為小數分隔符號的句號無法在 fr-fr 文化特性中剖析的字串,以及以空白字元作為群組分隔符號的字串,以及以空格分隔的十進位分隔符號,無法在 en-us 和非變異文化特性中進行剖析。
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)
剖析通常會發生在兩個內容中:
作為一項作業,其設計目的是要將使用者輸入轉換成數值。
作為設計來反復存取數值的作業;也就是還原序列化先前序列化為字串的數值。
下列各節會更詳細地討論這兩項作業。
剖析使用者字串
當您剖析使用者輸入的數值字串時,您應該一律將 NumberFormatInfo 反映使用者文化設定的物件具現化。 如需如何具現化 NumberFormatInfo 反映使用者自訂之物件的相關資訊,請參閱 >numberformatinfo 和動態資料 一節。
下列範例說明會反映使用者文化設定的剖析作業與不存在的使用者文化設定之間的差異。 在此情況下,預設系統文化特性是 en-us,但使用者已定義 "," 作為小數符號,"." 則是主控台、 地區和語言 中的群組分隔符號。 一般來說,這些符號會以預設的 en-us 文化特性反轉。 當使用者輸入反映使用者設定的字串,且字串是由 NumberFormatInfo 也反映使用者設定 (覆寫) 的物件所剖析時,剖析作業會傳回正確的結果。 不過,當以 NumberFormatInfo 反映標準 en-us 文化特性設定的物件剖析字串時,會對群組分隔符號的逗號符號產生錯誤,並傳回不正確的結果。
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
序列化和還原序列化數值資料
當數值資料以字串格式序列化,並在稍後還原序列化和剖析時,應使用不因文化特性而異的慣例來產生和剖析字串。 格式設定和剖析作業一律不會反映特定文化特性的慣例。 如果使用特定文化特性的設定,則資料的可攜性會受到嚴格限制;只有在其文化特性特定設定與序列化之執行緒相同的執行緒上,才能成功還原序列化。 在某些情況下,這表示資料甚至無法在已序列化的相同系統上成功還原序列化。
下列範例說明違反此原則時可能發生的情況。 當目前線程使用 en-us 文化特性的文化特性特定設定時,陣列中的浮點值會轉換成字串。 然後,資料會由使用 pt-BR 文化特性之文化特性特定設定的執行緒進行剖析。 在此情況下,雖然每個剖析作業都會成功,但資料並不會成功地往返,而且會發生資料損毀。 在其他情況下,剖析作業可能會失敗,而且 FormatException 可能會擲回例外狀況。
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
public class Example
{
public static void Main()
{
CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
PersistData();
CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("pt-BR");
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()
CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
PersistData()
CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("pt-BR")
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 類別的可寫入新執行個體。 |
屬性
CurrencyDecimalDigits |
取得或設定要在貨幣值中使用的小數位數。 |
CurrencyDecimalSeparator |
取得或設定要做為貨幣值中小數分隔符號的字串。 |
CurrencyGroupSeparator |
取得或設定分隔貨幣值中小數點左邊數字群組的字串。 |
CurrencyGroupSizes |
取得或設定貨幣值內小數點左邊數字的各個群組中的位數。 |
CurrencyNegativePattern |
取得或設定負數貨幣值的格式模式。 |
CurrencyPositivePattern |
取得或設定正數貨幣值的格式模式。 |
CurrencySymbol |
取得或設定要做為貨幣符號的字串。 |
CurrentInfo |
取得根據目前文化特性格式化值的唯讀 NumberFormatInfo。 |
DigitSubstitution |
取得或設定數值,指定圖形使用者介面顯示數字圖案的方式。 |
InvariantInfo |
取得與文化特性無關 (非變異) 的唯讀 NumberFormatInfo 物件。 |
IsReadOnly |
取得值,表示這個 NumberFormatInfo 物件是否為唯讀。 |
NaNSymbol |
取得或設定代表 IEEE NaN (Not a Number) 值的字串。 |
NativeDigits |
取得或設定字串陣列,其中包含對等於西方數字 0 到 9 之當地慣用的數字。 |
NegativeInfinitySymbol |
取得或設定代表負無限大的字串。 |
NegativeSign |
取得或設定代表相關數字為負數的字串。 |
NumberDecimalDigits |
取得或設定要在數值中使用的小數位數。 |
NumberDecimalSeparator |
取得或設定要做為數值中小數分隔符號的字串。 |
NumberGroupSeparator |
取得或設定分隔數值中小數點左邊數字群組的字串。 |
NumberGroupSizes |
取得或設定數值內小數點左邊數字的各個群組中的位數。 |
NumberNegativePattern |
取得或設定負數值的格式模式。 |
PercentDecimalDigits |
取得或設定要在百分比值中使用的小數位數。 |
PercentDecimalSeparator |
取得或設定要做為百分比值中小數分隔符號使用的字串。 |
PercentGroupSeparator |
取得或設定百分比值中分隔小數點左邊數字群組的字串。 |
PercentGroupSizes |
取得或設定百分比值內小數點左邊數字的各個群組中的位數。 |
PercentNegativePattern |
取得或設定負數百分比值的格式模式。 |
PercentPositivePattern |
取得或設定正數百分比值的格式模式。 |
PercentSymbol |
取得或設定要當做百分比符號的字串。 |
PerMilleSymbol |
取得或設定要當做千分之一符號的字串。 |
PositiveInfinitySymbol |
取得或設定代表正無限大的字串。 |
PositiveSign |
取得或設定用來表示相關數字為正數的字串。 |
方法
Clone() |
建立 NumberFormatInfo 物件的淺層複本 (Shallow Copy)。 |
Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
GetFormat(Type) |
取得指定類型的物件,以提供數字格式化服務。 |
GetHashCode() |
做為預設雜湊函式。 (繼承來源 Object) |
GetInstance(IFormatProvider) |
取得與指定的 NumberFormatInfo 相關聯的 IFormatProvider。 |
GetType() |
取得目前執行個體的 Type。 (繼承來源 Object) |
MemberwiseClone() |
建立目前 Object 的淺層複製。 (繼承來源 Object) |
ReadOnly(NumberFormatInfo) |
傳回唯讀的 NumberFormatInfo 包裝函式。 |
ToString() |
傳回代表目前物件的字串。 (繼承來源 Object) |