본문 바로가기
프로그래밍/c#

[c#] string.Format 서식

by 그래도동 2021. 1. 26.
728x90
반응형

서식항목

{index[,alignment][:formatString]}

 

var value = String.Format("{0,-10:C}", 126347.89m);         
Console.WriteLine(value);

 

index
문자열 표현이 문자열의이 위치에 포함 될 인수의 인덱스 (0부터 시작)입니다. 이 인수가 이면 null 문자열의이 위치에 빈 문자열이 포함 됩니다.

 

Alignment
선택 사항입니다. 인수가 삽입 되는 필드의 전체 길이와 오른쪽에 맞출지 (양의 정수) 아니면 왼쪽 맞춤 (음의 정수)을 나타내는 부호 있는 정수입니다. 맞춤 을 생략 하면 해당 인수의 문자열 표현이 선행 또는 후행 공백이 없는 필드에 삽입 됩니다.

Alignment 의 값이 삽입할 인수의 길이 보다 작은 경우 맞춤 은 무시 되 고 인수의 문자열 표현 길이가 필드 너비로 사용 됩니다.

 

formatString
선택 사항입니다. 해당 인수의 결과 문자열의 형식을 지정 하는 문자열입니다. FormatString 을 생략 하는 경우 해당 인수의 매개 변수가 없는 ToString 메서드를 호출 하 여 해당 문자열 표현을 생성 합니다. FormatString 을 지정 하는 경우 서식 항목에서 참조 하는 인수는 인터페이스를 구현 해야 합니다 IFormattable . 형식 문자열을 지 원하는 형식은 다음과 같습니다.

  • 모든 정수 계열 및 부동 소수점 형식
  • DateTime, DateTimeOffset
  • 모든 열거형 형식
  • TimeSpan
  • GUID

 

사용자 지정 서식 지정 작업

 

형식의 매개 변수가 있는 메서드의 오버 로드 중 하나를 호출 Format provider IFormatProvider 하 여 사용자 지정 서식 지정 작업을 수행할 수도 있습니다. 예를 들어 정수를 id 또는 전화 번호로 지정할 수 있습니다. 사용자 지정 서식 지정을 수행 하려면 provider 인수에서 및 인터페이스를 모두 구현 해야 합니다 IFormatProvider ICustomFormatter . Format메서드에 구현이 인수로 전달 되 면 ICustomFormatter provider Format 메서드는 해당 IFormatProvider.GetFormat 구현을 호출 하 고 형식의 개체를 요청 합니다 ICustomFormatter . 그런 다음 반환 된 개체의 메서드를 호출 하 여 ICustomFormatter Format 전달 된 복합 문자열의 각 형식 항목에 서식을 지정 합니다.

 

using System;

public class TestFormatter
{
   public static void Main()
   {
      int acctNumber = 79203159;
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0}", acctNumber));
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0:G}", acctNumber));
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0:S}", acctNumber));
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0:P}", acctNumber));
      try {
         Console.WriteLine(String.Format(new CustomerFormatter(), "{0:X}", acctNumber));
      }
      catch (FormatException e) {
         Console.WriteLine(e.Message);
      }
   }
}

public class CustomerFormatter : IFormatProvider, ICustomFormatter
{
   public object GetFormat(Type formatType) 
   {
      if (formatType == typeof(ICustomFormatter))        
         return this; 
      else
         return null;
   }
   
   public string Format(string format, 
                         object arg, 
                         IFormatProvider formatProvider) 
   {                       
      if (! this.Equals(formatProvider))
      {
         return null;
      }
      else
      {
         if (String.IsNullOrEmpty(format)) 
            format = "G";
         
         string customerString = arg.ToString();
         if (customerString.Length < 8)
            customerString = customerString.PadLeft(8, '0');
         
         format = format.ToUpper();
         switch (format)
         {
            case "G":
               return customerString.Substring(0, 1) + "-" +
                                     customerString.Substring(1, 5) + "-" +
                                     customerString.Substring(6);
            case "S":                          
               return customerString.Substring(0, 1) + "/" +
                                     customerString.Substring(1, 5) + "/" +
                                     customerString.Substring(6);
            case "P":                          
               return customerString.Substring(0, 1) + "." +
                                     customerString.Substring(1, 5) + "." +
                                     customerString.Substring(6);
            default:
               throw new FormatException( 
                         String.Format("The '{0}' format specifier is not supported.", format));
         }
      }   
   }
}
// The example displays the following output:
//       7-92031-59
//       7-92031-59
//       7/92031/59
//       7.92031.59
//       The 'X' format specifier is not supported.

 

 

 

 

출처

String.Format 메서드 (System) | Microsoft Docs

728x90
반응형

'프로그래밍 > c#' 카테고리의 다른 글

[c#] CreateParams 사용  (0) 2021.01.28
[c#] Region, 소스정리  (0) 2021.01.28
[Tip] Visual Studio 단축키  (0) 2021.01.19
[c#] 프로그램 시작시 중복 체크  (0) 2021.01.12
[c#] STAThread/COM(Component Object Model)  (0) 2021.01.12

댓글