언어/자바

[자바] String.format 메소드 사용법

believekim 2024. 12. 2. 12:14

 

참고 java 8 Docs

https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#Formatter--

 

Formatter (Java Platform SE 8 )

'e' '\u0065' Requires the output to be formatted using computerized scientific notation. The localization algorithm is applied. The formatting of the magnitude m depends upon its value. If m is NaN or infinite, the literal strings "NaN" or "Infinity", resp

docs.oracle.com

 

 

 

String.format()에서 형식 지정자는 % 기호 뒤에 오는 문자로 결정

%d 정수(integer)를 출력 String.format("%d", 42) → "42"
%f 부동소수점(float)을 출력 String.format("%.2f", 3.14159) → "3.14"
%s 문자열(string)을 출력 String.format("%s", "Hello") → "Hello"
%c 단일 문자(character)를 출력 String.format("%c", 'A') → "A"
%b 불리언(boolean)을 출력 String.format("%b", true) → "true"

 

 

 

 

1. 숫자 포맷팅


  • 앞에 0 채우기
int number = 42;
System.out.println(String.format("%05d", number)); // 출력: 00042

 

 

  • 부호 표시
int number = 42;
int negative = -42;
System.out.println(String.format("%+d", number));  // 출력: +42
System.out.println(String.format("%+d", negative)); // 출력: -42

 

 

  • 3자리 마다 콤마로 구분
int amount = 12345678;
System.out.println(String.format("%,d", amount)); // 출력: 12,345,678

 

 

 

 

2. 실수 포맷팅


  • 소수점 이하 지정 자리까지 표시
double pi = 3.14159;
System.out.println(String.format("%.2f", pi)); // 출력: 3.14

 

 

  • 전체 길이와 소수점 자릿수 지정
double pi = 3.14159;
System.out.println(String.format("%8.2f", pi)); // 출력: "    3.14" (총 8자리)

 

 

  • 소수 포함 3자리 마다 콤마로 구분
double amount = 12345678.90123;
System.out.println(String.format("%,.2f", amount)); // 출력: 12,345,678.90

 

 

 

3. 문자열 포맷팅


  • 오른쪽 정렬, 왼쪽 정렬
String text = "Hello";
System.out.println(String.format("%10s", text));  // 출력: "     Hello"
System.out.println(String.format("%-10s", text)); // 출력: "Hello     "

 

 

 

4. 특수 문자 처리


  • % 는 %%로 입력해야 출력 가능
System.out.println(String.format("Success rate: %.2f%%", 99.5)); // 출력: "Success rate: 99.50%"

 

 

 

  • "(큰따옴표)와 '(작은따옴표)는 \"와 \'로 입력해야 출력 가능
System.out.println(String.format("She said: \"%s\"", "Hello"));
// 출력: She said: "Hello"

System.out.println(String.format("It\'s a sunny day."));
// 출력: It's a sunny day.