C# 에서 숫자 형식에 관한 내용인데, 자주 찾게 되는 내용이라서 여기에 올립니다.
표준 숫자 형식 문자열은 일반 숫자 형식을 지정하는 데 사용됩니다. 표준 숫자 형식 문자열에는 Axx 형식을 사용합니다. 여기서 A는 영문자로서 형식 지정자라고 하며 xx는 선택적 정수로서 전체 자릿수 지정자라고 합니다. 전체 자릿수 지정자는 0에서 99 사이의 정수이며 결과의 자릿수에 영향을 줍니다. 공백을 포함하여 영문자가 두 개 이상 포함된 숫자 형식 문자열은 사용자 지정 숫자 형식 문자열로 해석됩니다.
다음 표에서는 표준 숫자 형식 지정자를 설명합니다. 각 형식 지정자에 의해 생성되는 출력 예는 표준 숫자 형식 문자열 출력 예제를 참조하십시오. 자세한 내용은 표 아래의 설명을 참조하십시오.
형식 지정자 | 이름 | 설명 | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
C 또는 c |
통화 |
숫자를 통화량을 나타내는 문자열로 변환합니다. 이 변환은 현재 NumberFormatInfo 개체의 통화 형식 정보에 의해 제어됩니다. 전체 자릿수 지정자는 필요한 소수 자릿수를 나타냅니다. 전체 자릿수 지정자를 생략하면 현재 NumberFormatInfo 개체에서 제공하는 기본 통화 전체 자릿수가 사용됩니다. | |||||||||||||||
D 또는 d |
10진수 |
이 형식은 정수 계열 형식에만 사용할 수 있습니다. 숫자를 10진수(0-9) 문자열로 변환하며, 숫자가 음수이면 앞에 빼기 부호가 붙습니다. 전체 자릿수 지정자는 결과 문자열에서 요구하는 최소 자릿수를 나타냅니다. 필요하면 수의 왼쪽을 0으로 채워서 전체 자릿수 지정자에서 지정한 자릿수를 만듭니다. | |||||||||||||||
E 또는 e |
과학적(지수) |
숫자를 "-d.ddd…E+ddd" 또는 "-d.ddd…e+ddd" 형태의 문자열로 변환하는데, 여기서 각 'd'는 숫자(0-9)를 나타냅니다. 숫자가 음수이면 문자열 앞에 빼기 부호가 붙습니다. 소수점 앞에는 항상 숫자가 하나 있어야 합니다. 전체 자릿수 지정자는 소수점 뒤에 필요한 자릿수를 나타냅니다. 전체 자릿수 지정자가 생략되면 소수점 뒤에 기본 6자리가 사용됩니다. 형식 지정자의 대/소문자에 따라 지수에 'E' 또는 'e' 접두사를 붙일 것인지가 결정됩니다. 지수는 항상 더하기 또는 빼기 기호가 포함된 최소 3자리로 구성됩니다. 필요하면 지수를 0으로 채워서 이 조건을 만족시킵니다. | |||||||||||||||
F 또는 f |
고정 소수점 |
숫자를 "-ddd.ddd…" 형태의 문자열로 변환하는데, 여기서 각 'd'는 10진수(0-9)를 나타냅니다. 숫자가 음수이면 문자열 앞에 빼기 부호가 붙습니다. 전체 자릿수 지정자는 필요한 소수 자릿수를 나타냅니다. 전체 자릿수 지정자를 생략하면 현재 NumberFormatInfo 개체에서 제공하는 기본 숫자 전체 자릿수가 사용됩니다. | |||||||||||||||
G 또는 g |
일반 |
숫자의 형식 및 전체 자릿수 지정자의 유무에 따라 숫자를 고정 소수점 또는 과학적 표기법 중에서 더 간단한 형식으로 변환합니다. 전체 자릿수 지정자가 생략되거나 0이면 다음 목록에 표시된 대로 숫자의 형식에 따라 기본 자릿수가 결정됩니다.
숫자를 과학적 표기법으로 나타낸 값이 -5보다 크고 전체 자릿수 지정자보다 작으면 고정 소수점 표기법이 사용되고 그렇지 않으면 과학적 표기법이 사용됩니다. 필수 0과 뒤에 붙는 0이 생략되면 결과에 소수점이 표시됩니다. 전체 자릿수 지정자가 있고 결과의 유효 숫자가 지정된 자릿수를 초과하면 뒤에 오는 초과 자릿수는 반올림을 통해 제거됩니다. 숫자가 Decimal이고 전체 자릿수 지정자가 생략된 경우에는 예외입니다. 이 경우 항상 고정 소수점 표기법이 사용되며 뒤에 오는 0은 그대로 표시됩니다. 과학적 표기법이 사용되면 형식 지정자가 'G'인 경우 결과의 지수 값 앞에 'E'가 붙고 형식 지정자가 'g'인 경우 앞에 'e'가 붙습니다.
|
N 또는 n
|
숫자
| 숫자를 "-d,ddd,ddd.ddd…" 형태의 문자열로 변환합니다. 여기서 '-'는 필요한 경우 음수 부호를 나타내고, 'd'는 숫자(0-9)를 나타내고, ','는 숫자 그룹 사이의 1000 단위 구분 기호를 나타내고, '.'는 소수점 기호를 나타냅니다. 실제 음수 패턴, 숫자 그룹 크기, 1000 단위 구분 기호 및 소수 구분 기호는 현재 NumberFormatInfo 개체에서 지정됩니다. 전체 자릿수 지정자는 필요한 소수 자릿수를 나타냅니다. 전체 자릿수 지정자를 생략하면 현재 NumberFormatInfo 개체에서 제공하는 기본 숫자 전체 자릿수가 사용됩니다.
|
P 또는 p
|
백분율
| 숫자를 NumberFormatInfo.PercentNegativePattern 속성(숫자가 음수인 경우) 또는 NumberFormatInfo.PercentPositivePattern 속성(숫자가 양수인 경우)에서 정의한 백분율을 나타내는 문자열로 변환합니다. 변환된 수는 100을 곱하여 백분율로 표시됩니다. 전체 자릿수 지정자는 필요한 소수 자릿수를 나타냅니다. 전체 자릿수 지정자를 생략하면 현재 NumberFormatInfo 개체에서 제공하는 기본 숫자 전체 자릿수가 사용됩니다.
|
R 또는 r
|
라운드트립
| 이 형식은 Single 및 Double 형식에만 사용할 수 있습니다. 라운드트립 지정자는 문자열로 변환된 숫자 값이 같은 숫자 값으로 다시 구문 분석될 수 있도록 보장해 줍니다. 이 지정자를 사용하여 숫자 값 형식을 지정하면 Double에는15자리의 전체 자릿수를, Single에는 7자리의 전체 자릿수를 가진 일반 형식을 사용하여 숫자 값을 먼저 테스트합니다. 이 값이 같은 숫자 값으로 다시 구문 분석되면 일반 형식 지정자를 통해 형식이 지정됩니다. 그러나 이 값이 같은 숫자 값으로 다시 구문 분석되지 못하면, Double에는 17자리 전체 자릿수를, Single에는 9자리 전체 자릿수를 사용하여 이 값의 형식이 지정됩니다. 전체 자릿수 지정자가 있더라도 무시됩니다. 이 지정자를 사용할 때는 라운드트립이 전체 자릿수보다 우선합니다.
|
X 또는 x
|
16진수
| 이 형식은 정수 계열 형식에만 사용할 수 있습니다. 숫자를 16진 문자열로 변환합니다. 형식 지정자의 대/소문자는 9보다 큰 16진수에 대문자를 사용할 것인지 또는 소문자를 사용할 것인지를 나타냅니다. 예를 들어, 'X'를 사용하면 "ABCDEF"를 생성하고 'x'를 사용하면 "abcdef"를 생성합니다. 전체 자릿수 지정자는 결과 문자열에서 요구하는 최소 자릿수를 나타냅니다. 필요하면 수의 왼쪽을 0으로 채워서 전체 자릿수 지정자에서 지정한 자릿수를 만듭니다.
|
기타 모든 단일 문자
|
알 수 없는 지정자
| 알 수 없는 지정자는 런타임 형식 예외를 throw합니다. 설명제어판 설정제어판에 있는 국가 및 언어 옵션 항목의 설정은 형식 지정 작업으로 생성되는 결과 문자열에 영향을 줍니다. 이러한 설정은 현재 스레드 culture와 연결된 NumberFormatInfo 개체를 초기화하는 데 사용됩니다. 현재 스레드 culture는 형식을 제어하는 데 사용되는 값을 제공합니다. 다른 설정을 사용하는 컴퓨터는 다른 결과 문자열을 생성합니다. NumberFormatInfo 속성형식 지정 작업은 현재 NumberFormatInfo 개체의 속성에 따라 영향을 받으며 이 개체는 현재 스레드 culture에 의해 암시적으로 제공되거나 형식 지정 작업을 호출하는 메서드의 IFormatProvider 매개 변수를 통해 명시적으로 제공됩니다. 이 매개 변수에는 NumberFormatInfo 또는 CultureInfo 개체를 지정합니다. 정수 계열 및 부동 소수점 숫자 형식표준 숫자 형식 지정자에 대한 설명 중에는 정수 계열 및 부동 소수점 숫자 형식이 언급되어 있습니다. 정수 계열 숫자 형식은 Byte, SByte, Int16, Int32, Int64, UInt16, UInt32 및 UInt64이고, 부동 소수점 숫자 형식은 Decimal, Single 및 Double입니다. 부동 소수점 무한대 및 NaN형식 문자열에 관계없이 Single 또는 Double 부동 소수점 형식의 값이 양의 무한대, 음의 무한대 또는 NaN(Not a Number)이면 형식이 지정된 문자열은 각각 현재 적용 가능한 NumberFormatInfo 개체에서 지정하는 해당 PositiveInfinitySymbol, NegativeInfinitySymbol 또는 NaNSymbol 속성의 값입니다. 예제다음 코드 예제에서는 스레드 현재 culture, 지정된 culture 및 모든 표준 숫자 형식 지정자를 사용하여 정수 계열 및 부동 소수점 숫자 값의 형식을 지정합니다. 이 코드 예제에서는 두 개의 특정 숫자 형식을 사용하지만 숫자 기본 형식(Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Decimal, Single 및 Double)의 경우에도 비슷한 결과가 생성됩니다. // This code example demonstrates the ToString(String) and // ToString(String, IFormatProvider) methods for integral and // floating-point numbers, in conjunction with the standard // numeric format specifiers. // This code example uses the System.Int32 integral type and // the System.Double floating-point type, but would yield // similar results for any of the numeric types. The integral // numeric types are System.Byte, SByte, Int16, Int32, Int64, // UInt16, UInt32, and UInt64. The floating-point numeric types // are Decimal, Single, and Double. using System; using System.Globalization; using System.Threading; class Sample { public static void Main() { // Format a negative integer or floating-point number in various ways. int integralVal = -12345; double floatingVal = -1234.567d; string msgCurrency = "(C) Currency: . . . . . . "; string msgDecimal = "(D) Decimal:. . . . . . . "; string msgScientific = "(E) Scientific: . . . . . "; string msgFixedPoint = "(F) Fixed point:. . . . . "; string msgGeneral = "(G) General (default):. . "; string msgNumber = "(N) Number: . . . . . . . "; string msgPercent = "(P) Percent:. . . . . . . "; string msgRoundTrip = "(R) Round-trip: . . . . . "; string msgHexadecimal = "(X) Hexadecimal:. . . . . "; string msg1 = "Use ToString(String) and the current thread culture.\n"; string msg2 = "Use ToString(String, IFormatProvider) and a specified culture.\n"; string msgCulture = "Culture:"; string msgIntegralVal = "Integral value:"; string msgFloatingVal = "Floating-point value:"; CultureInfo ci; // Console.Clear(); Console.WriteLine("Standard Numeric Format Specifiers:\n"); // Display the values. Console.WriteLine(msg1); // Display the thread current culture, which is used to format the values. ci = Thread.CurrentThread.CurrentCulture; Console.WriteLine("{0,-26}{1}", msgCulture, ci.DisplayName); // Display the integral and floating-point values. Console.WriteLine("{0,-26}{1}", msgIntegralVal, integralVal); Console.WriteLine("{0,-26}{1}", msgFloatingVal, floatingVal); Console.WriteLine(); // Use the format specifiers that are only for integral types. Console.WriteLine("Format specifiers only for integral types:"); Console.WriteLine(msgDecimal + integralVal.ToString("D")); Console.WriteLine(msgHexadecimal + integralVal.ToString("X")); Console.WriteLine(); // Use the format specifier that is only for the Single and Double // floating-point types. Console.WriteLine("Format specifier only for the Single and Double types:"); Console.WriteLine(msgRoundTrip + floatingVal.ToString("R")); Console.WriteLine(); // Use the format specifiers that are for integral or floating-point types. Console.WriteLine("Format specifiers for integral or floating-point types:"); Console.WriteLine(msgCurrency + floatingVal.ToString("C")); Console.WriteLine(msgScientific + floatingVal.ToString("E")); Console.WriteLine(msgFixedPoint + floatingVal.ToString("F")); Console.WriteLine(msgGeneral + floatingVal.ToString("G")); Console.WriteLine(msgNumber + floatingVal.ToString("N")); Console.WriteLine(msgPercent + floatingVal.ToString("P")); Console.WriteLine(); // Display the same values using a CultureInfo object. The CultureInfo class // implements IFormatProvider. Console.WriteLine(msg2); // Display the culture used to format the values. // Create a European culture and change its currency symbol to "euro" because // this particular code example uses a thread current UI culture that cannot // display the euro symbol (?). ci = new CultureInfo("de-DE"); ci.NumberFormat.CurrencySymbol = "euro"; Console.WriteLine("{0,-26}{1}", msgCulture, ci.DisplayName); // Display the integral and floating-point values. Console.WriteLine("{0,-26}{1}", msgIntegralVal, integralVal); Console.WriteLine("{0,-26}{1}", msgFloatingVal, floatingVal); Console.WriteLine(); // Use the format specifiers that are only for integral types. Console.WriteLine("Format specifiers only for integral types:"); Console.WriteLine(msgDecimal + integralVal.ToString("D", ci)); Console.WriteLine(msgHexadecimal + integralVal.ToString("X", ci)); Console.WriteLine(); // Use the format specifier that is only for the Single and Double // floating-point types. Console.WriteLine("Format specifier only for the Single and Double types:"); Console.WriteLine(msgRoundTrip + floatingVal.ToString("R", ci)); Console.WriteLine(); // Use the format specifiers that are for integral or floating-point types. Console.WriteLine("Format specifiers for integral or floating-point types:"); Console.WriteLine(msgCurrency + floatingVal.ToString("C", ci)); Console.WriteLine(msgScientific + floatingVal.ToString("E", ci)); Console.WriteLine(msgFixedPoint + floatingVal.ToString("F", ci)); Console.WriteLine(msgGeneral + floatingVal.ToString("G", ci)); Console.WriteLine(msgNumber + floatingVal.ToString("N", ci)); Console.WriteLine(msgPercent + floatingVal.ToString("P", ci)); Console.WriteLine(); } } /* This code example produces the following results: Standard Numeric Format Specifiers: Use ToString(String) and the current thread culture. Culture: English (United States) Integral value: -12345 Floating-point value: -1234.567 Format specifiers only for integral types: (D) Decimal:. . . . . . . -12345 (X) Hexadecimal:. . . . . FFFFCFC7 Format specifier only for the Single and Double types: (R) Round-trip: . . . . . -1234.567 Format specifiers for integral or floating-point types: (C) Currency: . . . . . . ($1,234.57) (E) Scientific: . . . . . -1.234567E+003 (F) Fixed point:. . . . . -1234.57 (G) General (default):. . -1234.567 (N) Number: . . . . . . . -1,234.57 (P) Percent:. . . . . . . -123,456.70 % Use ToString(String, IFormatProvider) and a specified culture. Culture: German (Germany) Integral value: -12345 Floating-point value: -1234.567 Format specifiers only for integral types: (D) Decimal:. . . . . . . -12345 (X) Hexadecimal:. . . . . FFFFCFC7 Format specifier only for the Single and Double types: (R) Round-trip: . . . . . -1234,567 Format specifiers for integral or floating-point types: (C) Currency: . . . . . . -1.234,57 euro (E) Scientific: . . . . . -1,234567E+003 (F) Fixed point:. . . . . -1234,57 (G) General (default):. . -1234,567 (N) Number: . . . . . . . -1.234,57 (P) Percent:. . . . . . . -123.456,70% */ 참고 항목 |