JAVA LPAD (ex: 자리수만큼 좌측부터 숫자 채우기)

JAVA LPAD (ex: 자리수만큼 좌측부터 숫자 채우기)

lpad는 좌측부터 자리수만큼 숫자 채우기, rpad는 우측부터 자리수만큼 숫자 채우기하는 SQL 함수 이름이다.

해당 기능의 함수를 따로 만들어쓰는 편인데, 귀찮다면 내장되어 있는 String.format 함수를 쓰면 된다.

String.format(“%06d”, 999);

== > 000999 가 된다.

응용해서 쓰면 됨.

예제 (오늘 날짜 가져오기)

     cal = Calendar.getInstance();
     StringBuffer today = new StringBuffer();
     today.append(“#”);
     today.append(String.format(“%04d”, cal.get(cal.YEAR)));
     today.append(“/”);
     today.append(String.format(“%02d”, cal.get(cal.MONTH) + 1));
     today.append(“/”);
     today.append(String.format(“%02d”, cal.get(cal.DAY_OF_MONTH)));
     today.append(” “);
     today.append(String.format(“%02d”, cal.get(cal.HOUR_OF_DAY)));
     today.append(“:”);
     today.append(String.format(“%02d”, cal.get(cal.MINUTE)));
     today.append(“:”);
     today.append(String.format(“%02d”, cal.get(cal.SECOND)));
     today.append(lineSeperator);