본문 바로가기
코딩 책공부/초보자를 위한 C# 200제 2판

형식지정자를 사용하는 String.Foramt() 과 ToString()

by FourthWay 2024. 3. 30.
728x90
반응형

형식지정자는 크게 두가지로 나눌 수 있다.

하나는 표준 형식지정자이고,

다른 하나는 커스텀 형식지정자 이다.

많이 사용하는 숫자 표준 형식지정자는 N(Number), D(Decimal), C(Currency), F(Fixed Point), E(Scientific) 이다.

이들 지정자는 숫자를 사용하여 정밀도를 표현할 수 있다.

더보기

Console.WriteLine("{0:N2}", 1234.5678);  //출력 : 1,234.57

Console.WriteLine("{0:D8}", 1234);           //출력 : 00001234

Console.WriteLine("{0:F3}", 1234.56);      //출력 : 1234.560

이러한 형식지정자는 Console.WriteLine()에서도 사용되는데 Console.WriteLine()뿐만 아니라

String.Format()과 ToString()에서도 똑같이 사용될 수 있다.

 

또 하나 유용한 기능이 커스텀 형식지정자 이다. 다음과 같은 기호를 이용하여 쉽게 포멧을 지정할 수 있다.

예를 들어 소수점 아래 두 자리까지만 표시하고 싶다면 {"#.##"}을 쓰면 된다.

세자리 마다 콤마 포시를 하고 소수점 두 자리까지 표시한다면 {"#,#.##"}로 쓰면 된다.

 

더보기

# : Digit placeholder(0이 앞에 붙지 않음)

0 : Zero placeholder(0이 앞에 붙음)

.  : 소수점(Decimal point)

,  : 천 자리(Thousands operator)

;  : 섹션 구분 기호(Section separator)

섹션 구분 기호(Section separator)는 독특한 기능을 한다. 숫자를 표시할 때 양수, 음수, 0의 값을 세미콜론으로 구분하여 제각기 다른  포멧으로 출력할 수 있다. 예를 들어 회계에서 음수123을 -123이 아니고 (123)으로 표시한다.

이럴 때 "{#,##0;(#,##0);zero)}" 포멧을 쓰면 음수는 괄호 안에 숫자로, 0은 zero로 출력한다.

 

using System;

namespace _047_A011_ForamtSpecifier
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("{0:N2}", 1234.5678);
            Console.WriteLine("{0:D8}", 1234);
            Console.WriteLine("{0:F3}", 1234.56);
            Console.WriteLine("{0:8}", 1234);
            Console.WriteLine("{0:-8}", 1234);

            string s;
            s = string.Format("{0:N2}", 1234.5678);
            Console.WriteLine(s);
            s = string.Format("{0:D8}", 1234);
            Console.WriteLine(s);
            s = string.Format("{0:F3}", 1234.56);
            Console.WriteLine(s);

            Console.WriteLine(1234.5678.ToString("N2"));
            Console.WriteLine(1234.ToString("D8"));
            Console.WriteLine(1234.56.ToString("F3"));

            Console.WriteLine("{0:#.##}", 1234.5678);
            Console.WriteLine("{0:0,0.00}", 1234.5678);
            Console.WriteLine("{0:#.#.##}", 1234.5678);
            Console.WriteLine("{0:000000.00}", 1234.5678);

            Console.WriteLine("{0:#,#.##;(#,#.##);zero}", 1234.567);
            Console.WriteLine("{0:#,#.##;(#,#.##);zero}", -1234.567);
            Console.WriteLine("{0:#,#.##;(#,#.##);zero}", 0);
        }
    }
}

728x90
반응형