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 。
次の例では、この3つの方法を使用し 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 。
次の例では、オブジェクトをインスタンス化する2つの方法を示し、 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
。 次の例では、現在のカルチャが英語 (米国) であり、通貨記号が既定値の $ から 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.UseUserOverrideプロパティがに設定されている場合、 true
プロパティ、 CultureInfo.DateTimeFormat CultureInfo.NumberFormat 、および CultureInfo.TextInfo もユーザー設定から取得されます。 ユーザー設定がオブジェクトに関連付けられているカルチャと互換性がない場合 CultureInfo (たとえば、選択したカレンダーがプロパティによって一覧表示されるカレンダーの1つではない場合など 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 NumberFormatInfo 静的メソッドに取得するオブジェクトを持つカルチャを表すオブジェクトを渡す GetInstance 。 返された NumberFormatInfo オブジェクトは読み取り/書き込み可能です。
メソッドを呼び出し、 CultureInfo.CreateSpecificCulture 返されたオブジェクトのプロパティの値を取得し CultureInfo NumberFormat ます。 返された NumberFormatInfo オブジェクトは読み取り/書き込み可能です。
クラスコンストラクターの1つ CultureInfo.CultureInfo を呼び出し、返されたオブジェクトのプロパティの値を取得し CultureInfo NumberFormat ます。 返された NumberFormatInfo オブジェクトは読み取り/書き込み可能です。
次の例では、これらの4つの方法を使用し 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 オブジェクトのインスタンス化
ニュートラルカルチャは、国/地域に依存しないカルチャまたは言語を表します。 通常は、1つまたは複数の特定のカルチャの親になります。 たとえば、fr は、フランス語と fr-fr カルチャの親のニュートラルカルチャです。 NumberFormatInfo NumberFormatInfo 特定のカルチャの書式指定規則を表すオブジェクトを作成するのと同じ方法で、ニュートラルカルチャの書式指定規則を表すオブジェクトを作成します。
注意
.NET Framework 3.5 以前のバージョンでは、ニュートラルカルチャの書式指定規則を反映するオブジェクトを取得しようとすると、 NumberFormatInfo 例外がスローさ NotSupportedException れます。
ただし、ニュートラルカルチャは特定の国/地域に依存しないため、カルチャ固有の書式情報がありません。 .NET Framework は、オブジェクトにジェネリック値を設定するのではなく、 NumberFormatInfo NumberFormatInfo ニュートラルカルチャの子である特定のカルチャの書式指定規則を反映するオブジェクトを返します。 たとえば、ニュートラルカルチャのオブジェクトには NumberFormatInfo en-us カルチャの書式指定規則が反映され、fr カルチャのオブジェクトには fr-fr NumberFormatInfo カルチャの書式指定規則が反映されます。
次のようなコードを使用して、各ニュートラルカルチャが表す特定のカルチャの書式指定規則を決定できます。
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 が安定しています。 その他のデータは、次の理由により、アプリケーションセッション間、または1つのセッション内でも変更される可能性があります。
システムの更新プログラム。 通貨記号や通貨の形式などのカルチャ設定は、時間の経過と共に変化します。 この場合、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 には、 という 1 つのメソッドが含まれています GetFormat(Type) 。 これは、書式設定情報を提供するために必要な型を表す オブジェクト Type を渡すコールバック メソッドです。 メソッドは、型のインスタンスを提供できない場合は、その型のインスタンスまたは を返 null
します。 次の.NET Frameworkは、数値を IFormatProvider 書式設定する 2 つの実装を提供します。
クラス 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 プロパティ
すべての書式設定操作では、標準またはカスタムの数値書式指定文字列を使用して、数値から結果文字列が生成されます。 場合によっては、次の例のように、書式指定文字列を使用して結果文字列を生成する方法が明示的です。 このコードでは、 メソッドを呼び出して、en-US カルチャの書式設定規則を使用して、値をさまざまな文字列形式 Decimal.ToString(IFormatProvider) Decimal に変換します。
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
それ以外の場合、書式指定文字列の使用は暗黙的です。 たとえば、次のメソッドで default メソッドまたは parameterless メソッドを呼び出す場合、インスタンスの値は、一般的 Decimal.ToString() な ("G") 書式指定子と現在のカルチャの規則 (この場合は Decimal 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
各標準数値書式指定文字列は、1 つ以上のプロパティを使用して、結果文字列で使用されるパターンまたはシンボル NumberFormatInfo を決定します。 同様に、"0" と "#" を除く各カスタム数値書式指定子は、プロパティによって定義される結果文字列にシンボルを挿入 NumberFormatInfo します。 次の表に、標準およびカスタムの数値書式指定子と、関連付けられているプロパティを示 NumberFormatInfo します。 特定のカルチャの結果文字列の外観を変更するには 、「Modifying NumberFormatInfo properties」セクションを参照 してください。 これらの書式指定子の使用の詳細については、「標準数値書式指定文字列」および「カスタム数値書式 指定 文字列 」を参照してください。
書式指定子 | 関連付けられているプロパティ |
---|---|
"C" または "c" (通貨書式指定子) | CurrencyDecimalDigits: 小数部の既定の桁数を定義します。 CurrencyDecimalSeparator (小数点の記号を定義します)。 CurrencyGroupSeparatorグループまたは桁区切り記号を定義する場合は 。 CurrencyGroupSizes整数グループのサイズを定義する場合は 。 CurrencyNegativePattern: 負の通貨値のパターンを定義します。 CurrencyPositivePattern: 正の通貨値のパターンを定義します。 CurrencySymbol:通貨記号を定義します。 NegativeSign (マイナス記号を定義します)。 |
"D" または "d" (10 進書式指定子) | 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" (16 進書式指定子) | [なし] : |
"."(小数点のカスタム書式指定子) | NumberDecimalSeparator (小数点の記号を定義します)。 |
"," (グループ区切り記号カスタム書式指定子) | NumberGroupSeparator: グループ (千単位) 区切り記号を定義します。 |
"%" (パーセントプレースホルダーカスタム書式指定子) | PercentSymbol。パーセント記号を定義します。 |
"‰" (per-mille プレースホルダーカスタム書式指定子ごと) | PerMilleSymbol、per-mille 記号ごとにを定義します。 |
"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 「 書式指定文字列と 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
National id 番号の書式設定
国識別番号の多くは、数字だけで構成されているため、オブジェクトのプロパティを変更することで簡単に書式設定でき 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 の各数値型には、とという2つのオーバーロードされた解析メソッドがあり 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)
解析は通常、次の2つのコンテキストで行われます。
ユーザー入力を数値に変換するように設計された操作として。
数値をラウンドトリップするように設計された操作として。つまり、以前に文字列としてシリアル化された数値を逆シリアル化します。
以下のセクションでは、これら2つの操作について詳しく説明します。
ユーザー文字列の解析
ユーザーによって入力された数値文字列を解析する場合は、ユーザーのカルチャ設定を反映するオブジェクトを常にインスタンス化する必要があり NumberFormatInfo ます。 ユーザーのカスタマイズを反映するオブジェクトをインスタンス化する方法については、 NumberFormatInfo 「 NumberFormatInfo and dynamic data 」セクションを参照してください。
次の例は、ユーザーのカルチャ設定を反映する解析操作と、それ以外の設定を比較した場合の違いを示しています。 この場合、既定のシステムカルチャは en-us ですが、ユーザーは、"," を小数点記号として定義し、[コントロールパネル]、[ 地域と言語] の桁区切り記号として "." を定義しています。 通常、これらのシンボルは既定の en-us カルチャでは逆になります。 ユーザー設定を反映する文字列を入力すると、ユーザー設定 (上書き) を反映するオブジェクトによって文字列が解析されると NumberFormatInfo 、解析操作によって正しい結果が返されます。 ただし、標準の en-us カルチャ設定を反映するオブジェクトによって文字列が解析された場合は、桁区切り記号の NumberFormatInfo コンマ記号が間違っていて、正しくない結果が返されます。
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 (非数) 値を表す文字列を取得または設定します。 |
NativeDigits |
西洋数字 0 ~ 9 に等しいネイティブ数字の文字列配列を取得または設定します。 |
NegativeInfinitySymbol |
負の無限大を表す文字列を取得または設定します。 |
NegativeSign |
関連付けられた数値が負であることを示す文字列を取得または設定します。 |
NumberDecimalDigits |
数値で使用する小数点以下の桁数を取得または設定します。 |
NumberDecimalSeparator |
数値で桁区切り記号として使用する文字列を取得または設定します。 |
NumberGroupSeparator |
数値で小数点の左にある数字のグループを区切る文字列を取得または設定します。 |
NumberGroupSizes |
数値で小数点の左にある各グループの数字の数を取得または設定します。 |
NumberNegativePattern |
負の数値の形式パターンを取得または設定します。 |
PercentDecimalDigits |
パーセント値で使用する小数点以下の桁数を取得または設定します。 |
PercentDecimalSeparator |
パーセント値で桁区切り記号として使用する文字列を取得または設定します。 |
PercentGroupSeparator |
パーセント値で小数点の左にある数字のグループを区切る文字列を取得または設定します。 |
PercentGroupSizes |
パーセント値で小数点の左にある各グループの数字の数を取得または設定します。 |
PercentNegativePattern |
負のパーセント値の形式パターンを取得または設定します。 |
PercentPositivePattern |
正のパーセント値の形式パターンを取得または設定します。 |
PercentSymbol |
パーセント記号として使用する文字列を取得または設定します。 |
PerMilleSymbol |
パーミル記号として使用する文字列を取得または設定します。 |
PositiveInfinitySymbol |
正の無限大を表す文字列を取得または設定します。 |
PositiveSign |
関連付けられた数値が正であることを示す文字列を取得または設定します。 |
メソッド
Clone() |
NumberFormatInfo オブジェクトの簡易コピーを作成します。 |
Equals(Object) |
指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。 (継承元 Object) |
GetFormat(Type) |
数値形式指定サービスを提供する指定した型のオブジェクトを取得します。 |
GetHashCode() |
既定のハッシュ関数として機能します。 (継承元 Object) |
GetInstance(IFormatProvider) |
指定された NumberFormatInfo に関連付けられている IFormatProvider を取得します。 |
GetType() |
現在のインスタンスの Type を取得します。 (継承元 Object) |
MemberwiseClone() |
現在の Object の簡易コピーを作成します。 (継承元 Object) |
ReadOnly(NumberFormatInfo) |
読み取り専用 NumberFormatInfo ラッパーを返します。 |
ToString() |
現在のオブジェクトを表す文字列を返します。 (継承元 Object) |