프로그래밍 & IT정보

[ JAVA ] String.format() 사용법. 예제.

작은딸기 2023. 3. 17. 10:00

안녕하세요.

String.format 사용방법에 대해서 알아보고자 합니다.

String.format 메서드는 지정된 형식에 따라 개체의 값을 문자열로 변환하여 다른 문자열에 삽입합니다.

%를 붙여서 문자열에 사용하면 그 위치에 변수의 값을 형식화하여 대입 삽입이 가능합니다.

public static String format(String format, Object... arg);
public static String format(Local l, String format, Object... args);

코딩 어렵지 않아요. 아래 예제 한 번씩 보시면 됩니다.


예제

① %s, %S : 문자열 출력 (String Formatting)

String result = "HelloW"; 

System.out.println(String.format("String :%s",result)); 
System.out.println(String.format("String :%S",result));

▶ 결과

String :HelloW
String :HELLOW [모두 대문자로 변환하여 출력]

 

② %d : 10진수 정수 (Integer Formatting)

int intValue = 123456; 
System.out.println(String.format("%d", intValue)); 
System.out.println(String.format("%,d", intValue)); 

System.out.println(String.format("%9d", intValue)); 
System.out.println(String.format("%-9d!", intValue)); 

System.out.println(String.format("%09d", intValue));

▶ 결과

123456 [ 그대로 출력 ]
123,456 [ %뒤에 , 를 붙이면 3자리 단위로 출력 ]
   123456 [ %뒤 숫자는 자리수를 뜻하며 value값이 9자리보다 못하므로 왼쪽에 3자리의 공백 ]
123456   ! [ %뒤 -는 왼쪽 정렬로 뒷편에 모자란 자리수를 공백처리. 여기서 !표는 공백을 보여주려고 예시로 입력 ]
000123456 [ $뒤 0을 입력하면 공백 대신 0을 채워서 출력 ]

③ %b, %B : 참, 거짓 (Boolean Formatting)

boolean bool = true; 
System.out.println(String.format("%B", bool)); 
System.out.println(String.format("%b ", bool));

▶ 결과

TRUE [ 대문자 변환 출력 ] 
true [ 그대로 출력 ]

 


④ Locale

LocalDateTime now = LocalDateTime.now(); 
int money = 10000; 
System.out.println(String.format(Locale.ENGLISH,"Today : %tp %<tY.%<tm.%<td", now)); 
System.out.println(String.format(Locale.US,"%,d $",money));
System.out.println(String.format(Locale.ITALY,"%,d €",money));

▶ 결과

Today : pm 2023. 03. 09. 
10,000 $ 
10.000

 


⑤ %f : 실수형 (Float Formatting)

double fValue = 12345.45678; 
System.out.println(String.format("%f", fValue)); 
System.out.println(String.format("%.3f", fValue)); 
System.out.println(String.format("%013.3f", fValue));

▶ 결과

12345.456780 
12345.457 [ .3은 소수점 3자리 출력 ] 
000012345.457 [ %뒤 013은 전체 13자리로 출력하되 앞 공백은 0으로 채움 ]