Java

[Java] 기본 API 클래스⑧ Format

망고고래 2024. 4. 6. 16:55

what?

데이터의 형식을 지정하는 클래스

why?

데이터의 형식을 통일해서 지정할 수 있음

how?

1)DecimalFormat 클래스

숫자 형식화

 

#: 있으면 출력

0: 없어도 0으로 채움

.: 소수점

-: 음수 기호를 붙임

,: 쉼표를 넣음

E: 지수 기호

%: 퍼센트

 

패턴 정의 후 인스턴스 생성, format 메서드 호출해서 문자열 반환

public class Format1{
    //패턴 지정
    String[] pattern = {
        "###.###",
        "000.000",
        "-###.###",
        "000000.00%"
    };
    
    //형식화 적용 전 수 배열
    double[] arr = {1.3, 3.33, 124.243, 242};
    
    for(int i = 0; i<pattern.length; i++){
        //DecimalFormat 인스턴스 생성
        DecimalFormat d = new DecimalFormat(pattern[i]);
        System.out.println("<<<<" + pattern[i] + ">>>>");
        for(int j = 0; j<arr.length; j++){
            //format() 호출
            System.out.println(d.format(arr[j]));
        }
    }
}

 

실행 결과

<<<<###.###>>>>
1.3
3.33
124.243
242
<<<<000.000>>>>
001.300
003.330
123.243
242.000
<<<<-###.###>>>>
-1.3
-3.3
-124.243
-242
<<<<000000.00%>>>>
000130.00%
000333.00%
012324.30%
035300.00%

 

 

2)SimpleDateFormat

날짜 형식화 클래스

y: 년

M: 월

d: 일

E: 요일

a: 오전/오후

H: 시간

m: 분

s: 초

 

원하는 패턴을 파라미터로 해서 SimpleDateFormat 인스턴스 생성, format() 사용

public class Format2{
    Date day = new Date();
    String patternKorea = "yyyy-MM-dd";
    String patternUSA = "MM-dd-yyyy";
    String patternUK = "dd-MM-yyyy";
    String pattern1 = "E요일 HH시 mm분 ss초";
    
    SimpleDateFormat p1 = new SimpleDateFormat(patternKorea);
    SimpleDateFormat p2 = new SimpleDateFormat(patternUSA);
    SimpleDateFormat p3 = new SimpleDateFormat(patternUK);
    SimpleDateFormat p4 = new SimpleDateFormat(pattern1);
    
    System.out.println("현재 날짜" + day);
    System.out.println("한국 형식(년, 월, 일): " + p1.format(day));
    System.out.println("미국 형식(월, 일, 년): " + p2.format(day));
    System.out.println("영국 형식(일, 월, 년): " + p3.format(day));
    System.out.println(p4.format(day));
}