상상 너머 그 무언가...

String.Format() 설명 본문

개발관련(Development)/유니티3D(Unity3D)

String.Format() 설명

Clack 2011. 3. 3. 14:00

OpneNI 관련된 unity sample 스크립트를 분석 중에 다음과 같은 스크립트를 보게 되었다.
Debug.Log(String.Format("[{0}] New user", UserId));
C# 레퍼런스를 찾아보니 콤마 뒤에 있는 UserId 변수에 있는 값이 {0} 위치에 대입되는 기능이였다.


대입시킬 값이 두개 이상이면 {1}, {2}... 이런식으로 index 숫자를 한개식 증가시켜 입력해주면 된다.
("{0}  {1}", "Decimal", "Hex")


뒤에오는 매개변수에 매칭되는 { } 문장은 단순 index값 뿐만이 아니라 옵션이 두가지 더 있다.

{index[,length][:formatString]}

한글로 옮겨 적자면 ==> {인텍스,길이:스트링포멧} 

예제를 보자

String.Format("{0,10:G}: {0,10:X}", value)

value변수의 값을 첫번째 {} 에서는 최대 10자리 길이로 출력하되 formatString 형식이 G(General,일반)라서 그대로 표현되고
두번째 {}에서는 최대 10자리 길이로 X형식으로 Hex(16진수)로 표현하라는 문장이다.

formatString형식은 뒤에 오는 매개변수 포멧에 따라 달라진다.
For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. For the standard format strings used with enumerations, see Enumeration Format Strings.

 


정수 및 소수 자리수 설정

"{0:D5}", 123    ===>  00123
"{0:E1}", 123.45  ====> 1.2E+002
"{0:F5}", 12.3   ====>  12.30000
"{0:G}", 34.56  ====>  34.56
"{0:N}", 100000000  ====> 100,000,000
"{0:P}, 0.65  ====> 65.00%
"{0:X} 254  ====>  FE