본문 바로가기

자바의 정석 정리

자바의 정석 - 10.2 형식화 클래스

10.2.1 DecimalFormat

  • 숫자 데이터를 정수, 부동소수점, 금액 등의 다양한 형식으로 표현
  • 텍스트 데이터를 숫자로 쉽게 변환
double number = 1234567.89;
DecimalFormat df = new DecimalFormat("#.#E0");
String result = df.format(number); //12.E6

10.2.2 SimpleDateFormat

  • 추상클래스 DateFormat의 구현체
  • 날짜를 출력할 때 사용
Date d = new Date();

SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat s2 = new SimpleDateFormat("''yy년 MM월 dd일 E요일");
SimpleDateFormat s3 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
SimpleDateFormat s4 = new SimpleDateFormat("오늘은 이 달의 F번째 E요일 입니다.");

s1.format(d); //2015-11-23
s2.format(d); //'15년 11월 23일 월요일
s3.format(d); //2015-11-23 03:46:49 오후
s4.format(d); //오늘은 이 다르이 4번째 월요일 입니다.
  • Calendar → Date
Calendar cal = Calendar.getInstance();
cal.set(2015, 9, 3); //2005년 10월 3일

Date d = cal.getTime();

SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd");
s1.format(d); //2005-10-3
  • parse()
DateFormat df = SimpledateFormat("yyyy년 MM월 dd일");
DateFormat df2 = SimpledateFormat("yyyy/MM/dd");

try{ //입력 형식의 불일치로 인한 에러 발생이 생길 수 있기 때문에 예외처리를 해 주어야 함.
    Date d = df.parse("2015년 11월 23일");
    System.out.println(df2.format(d)); //2015/11/23
}catch(Exception e){}

10.2.3 ChoiceFormat

  • 특정 범위에 속하는 값을 문자열로 변환
double[] limit = {60, 70, 80, 90}; //오르나순으로 정렬되어야 함
String[] grade = {"D", "C", "B", "A"}; //limint과 grades간의 순서와 개수를 맞춰야 함

int score = { 100, 95, 88, 70, 52, 60, 70 };

ChoiceFormat form = new ChoiceFormat(limit, grade);

for(int i=0; i<score.length; i++){
    System.out.println(score[i] + ":" + form.format(score[i]));
}

/*
limit과 grade가 맞지 않으면 ArgumentException발생
*/
  • 패턴
  • ':' 경계값 포함O
  • '<' 경계값 포함X
String pattern = "60#D|70#C|80<B|90#A";
int score = { 100, 95, 88, 70, 52, 60, 70 };
ChoiceFormat form = new ChoiceFormat(pattern);

10.2.4 MessageFormat

  • 데이터를 정해진 양식에 맞게 출력
String msg = "{0} {1} {2} {3}";
Object[][] arg = {
    {"a", "b", "c", "d"},
    {"1", "2", "3", "4"}
}

for(int i=0; o<arg.lenth; i++){
    String result = MessageFormat.format(msg, arg[i]);
}