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 USD로 통화 값을 표시 하도록 선택할 수 있습니다. 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 개체 (선택한 달력 중 하나가 아닌 달력으로 나열 하는 경우에 예를 들어를 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-CA 음성 캐나다의 영어 언어를 나타내는 특정 문화권입니다. 인스턴스화할 수 있습니다는 NumberFormatInfo 다음과 같은 방법으로 특정 문화권의 서식 규칙을 나타내는 개체입니다.
호출 하 여 합니다 CultureInfo.GetCultureInfo(String) 메서드와 반환된 된 값을 검색할 CultureInfo 개체의 NumberFormat 속성입니다. 반환 된 NumberFormatInfo 개체가 읽기 전용입니다.
전달 하 여는 CultureInfo 문화권을 나타내는 개체입니다 NumberFormatInfo static 검색 하려는 개체 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 예외가 throw 됩니다.
그러나 특정 국가/지역 독립적 이기 때문에 중립 문화권에 culture 별 서식 지정 정보를 없습니다. 채우기 대신를 NumberFormatInfo 반환 하는.NET Framework 제네릭 값 개체를 NumberFormatInfo 개체는 특정 형식 지정 규칙 문화권을 반영 하는 중립 문화권의 자식입니다. 예를 들어 합니다 NumberFormatInfo EN-US 문화권의 서식 규칙을 반영 하는 en 중립 문화권에 대 한 개체 및 NumberFormatInfo FR-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 및 dynamic data
제공 하는 숫자 값의 서식을 지정 하는 것에 대 한 culture 별 데이터를 NumberFormatInfo 클래스는 제공한 문화권 데이터와 마찬가지로 동적는 CultureInfo 클래스입니다. 에 대 한 값의 안정성에 대 한 어떠한가 정도 만들면 안 NumberFormatInfo 연결 된 개체를 특정 CultureInfo 개체입니다. 고정 문화권 및 연결 된 제공한 데이터만 NumberFormatInfo 개체 안정적입니다. 다른 데이터는 애플리케이션 세션 간에 또는 다음과 같은 이유로 단일 세션 내 에서도 변경할 수 있습니다.
시스템 업데이트. 시간에 따른 통화 기호, 통화 형식 등 문화권 기본 설정을 변경합니다. Windows 업데이트 변경 되어이 경우는 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 수정 속성 섹션입니다. 이러한 사용에 대 한 세부 정보 형식 지정자, 참조 Standard Numeric Format Strings 하 고 사용자 지정 숫자 서식 문자열합니다.
형식 지정자 | 연결된 속성 |
---|---|
"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백분율 기호를 정의 합니다. |
"‰" (단위: 분 율 자리 표시자 사용자 지정 형식 지정자) | 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 결과 문자열을 정의 하는 속성 참조를 서식 문자열 및 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
메서드는 문자열을 숫자로 변환 및 변환에 실패 하면 예외를 throw 합니다. 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 문화권을 구문 분석에 실패 하면 소수 구분 기호 그룹 구분 기호를 마침표와 쉼표를 포함 하는 문자열 및 문자열로 그룹 구분 기호로 white space 및 소수 구분 기호로 쉼표를 사용 하 여 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 및 dynamic data 섹션입니다.
다음 예제에서는 사용자 문화권 설정을 반영 하는 구문 분석 작업을 하지 않는 사이의 차이점을 보여 줍니다. 이 경우 기본 시스템 문화권은 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
직렬화 및 역직렬화 숫자 데이터
숫자 데이터 문자열 형식으로 직렬화 하 고 나중에 역직렬화 및 구문 분석을 하는 경우 문자열을 생성 하 고 고정 문화권의 규칙을 사용 하 여 구문 분석 해야 합니다. 서식 지정 및 구문 분석 작업을 특정 문화권의 규칙을 반영 하지 해야 합니다. 문화권별 설정을 사용 하는 경우 데이터의 이식성은 엄격 하 게 제한 합니다. culture 별 설정 되어 있는 직렬화된 스레드와 동일한 스레드에서 정상적으로 역직렬화할 수 있습니다. 경우에 따라 데이터에도 수 없습니다.이 즉 직렬화된 동일한 시스템에 성공적으로 역직렬화할 수 있습니다.
다음 예제에서는이 원칙을 위반 하는 경우 어떻게 하는 방법을 보여 줍니다. 배열에 부동 소수점 값은 현재 스레드의 EN-US 문화권의 문화권 관련 설정을 사용 하는 경우 문자열로 변환 됩니다. 그런 다음 pt-BR 문화권의 문화권별 설정을 사용 하는 스레드에 의해 데이터가 구문 분석 됩니다. 이 경우 각 구문 분석 작업이 성공 하지만 데이터가 라운드트립 하지 않고 데이터 손상이 발생 합니다. 다른 경우에는 구문 분석 작업 실패할 수 있습니다 및 FormatException 예외가 throw 될 수 있습니다.
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) |