커뮤니티
WP-자료실
제목:    C#, Using String.Formta() to format a value Number Format.String Examples
  3061   김윤중

http://www.java2s.com/Code/CSharp/Development-Class/UseStringFormattoformatavalue.htm

      

         int i = 1234;
        double d = 1234.5678;
        string s = "1234";

        string result = String.Format("{0} {1} {2}", i, d, s); 
        Console.WriteLine("{0}", result); //1234 1234.5678 1234

        result = String.Format("{0:###,###}", i); 

       Console.WriteLine(result); // 1,234
        Console.WriteLine( String.Format("{0:###,###.##}", d)); // 1,234.57

      String.Format(“0:D4“,12); //0012
     String.Format(“{0,4}“,12)  //  12 
        //
잘리는 부분은 반올림
        Console.WriteLine( String.Format("{0:###,##0.##0000}", d)); // 1,234.567800
        // #
은 데이터 없으면 빈칸이지만
        // 0
은 데이터 없으면 0으로 채운다.
        Console.WriteLine(String.Format("{0:000,###}", i)); // 001,234
        Console.WriteLine(String.Format("{0:000,###}", s)); //1234
        Console.WriteLine(String.Format("{0:000,###}", Convert.ToInt32(s))); // 001,234
        //
문자열에는 숫자 관련 포맷이 적용 안됨
        // DB
에서 읽어올 경우 문자열로 되어 있기 때문에 주의
        // Casting
해줌 : Convert.ToInt32(s) 문자 -> 숫자


        result = String.Format("{0}\n{1}\n{2}"
                                , " ");
        Console.WriteLine(result);

 

        // 긴 문자열 연결 : @기호공백, 줄바꿈 그대로 표현
        result = @"
           
            ";
        Console.WriteLine(result);

 

        // 긴 문자열 연결 : + 연산자
        result =
            " ";
        Console.WriteLine(result);

 

        // 채우기
        string data = "1234";
        Console.WriteLine("{0}", data.PadLeft(10, '*')); // ******1234


        //
지정한 폭(10)으로 폭 늘리고 왼쪽에 '*'을 삽입
        Console.WriteLine("{0}", data`(10, '*')); // 1234******