Soy's Devlog

Formatter - 지정된 형식으로 출력하기 본문

Dev/Java

Formatter - 지정된 형식으로 출력하기

소이리 2022. 1. 31. 22:47

java에서는 문자나 숫자, 날짜의 자리수를 맞춰 출력할 수 있는 Formatter 클래스를 제공한다.

사용하려면 java.util.Formatter를 import 해주면 된다.

 

공식문서에서 설명하는 Format은 이렇다.

public static String format(String format,
                            Object... args)

Returns a formatted string using the specified format string and arguments.


지정된 형식 문자열과 인수를 사용하여 형식이 지정된 문자열을 반환 한다고 한다. 이렇게만 보면 알기 어려우니 하나씩 뜯어보자!

 

기본 형식

  • 문자, 숫자

 %[argument_index$][flags][width][.precision]conversion
  • 날짜, 시간
%[argument_index$][flags][width]conversion
  • 필수 값 : % , conversion
  • [argument_index$] 
    파라미터의 인덱스를 의미한다. 
    첫 번째는 1$, 두 번째는 2$ 이렇게 타겟 대상의 순서를 지정할 때 쓴다.
    길이를 지정하고자 할 때는 $표시 뒤에 숫자를 입력해 주면 된다.  ex) 1$10 : 첫 번째 파라미터 길이를 10으로 지정
  • [flags] 
    ' - ' 는 문자열에만 사용할 수 있으며, 사용하면 왼쪽으로 정렬되고 사용하지 않으면 기본값인 오른쪽 정렬이 된다.
    만약 flag가 0 이라면 정수,실수에 한해 공백이 모두 0으로 채워진다.   ex) %-8s  : 왼쪽부터 정렬 , %8s : 오른쪽부터 정렬
    ' + ' 는 정수나 실수에서만 사용 할 수 있으며, 부호를 표시하면서 남는 자리는 0으로 채워진다.
           ex)( "%+20d%+20d", 30, -30 )->   +30  -30
    ' ( '  는 음수인 경우에만 사용할 수 있고 음수에만 표기된다.
    ' , '  를 포함하면 해당국가에서 사용되는 기호로 숫자를 표기해 준다.  ex) 1,000,000
  • [width]
    사용 할 문자의 최소 수
  • [.precision]
    사용할 문자의 최대 수, 부동소수점의 경우 소수점 뒤의 자리수를 의미한다.
  • conversion 
    표현 할 데이터의 타입을 의미한다. 
    s(문자열), d(10진수 정수), x(16진수), X(16진수 대문자), o(8진수), f(실수), c(숫자를 유니코드로 변환)
 System.out.println(String.format("%d", 100));

 System.out.println(String.format("%10d", 100));

 System.out.println(String.format("%+10d%+10d", 500, -500));

 System.out.println(String.format("%-20s", "message"));

 System.out.println(String.format("%20s", "message"));

 System.out.println(String.format("%10s%10s", "formatter","coding"));

 System.out.println(String.format("%x", 100));

 System.out.println(String.format("%o", 100));

 System.out.println(String.format("%10.5f", 1000.333f));

 System.out.println(String.format("%c", 100));
        
 //결과
100
       100
      +500      -500
message             
             message
 formatter    coding
64
144
1000.33301
d

 

 

 

참고

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

 

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

https://blog.jiniworld.me/68

'Dev > Java' 카테고리의 다른 글

입력된 정수의 자릿수 구하기  (0) 2022.01.30
Comments